[C#] Accelerate then decelerate to its wanted position

I have an object that needs to accelerate towards a location then decelerate to a given position using velocity’s.

Here’s what I have.

	public float decelDist;
	public float distanceTo;
	protected virtual void Movement() //Called from FixedUpdate
		float adjustedAccel;
		adjustedAccel = acceleration / rigidbody.mass;

		decelDist = ((new Vector3(Velocity.x * Velocity.x, 0, Velocity.z * Velocity.z)) / (2 * adjustedAccel)).magnitude;
		distanceTo = Vector3.Distance(transform.position, wantedPos);
		if(decelDist >= Vector3.Distance(transform.position, wantedPos))
			//slow down
			Velocity -= (wantedPos - transform.position).normalized * adjustedAccel;
			Debug.Log("slow down");
		else if (decelDist < Vector3.Distance(transform.position, wantedPos))
			Velocity += (wantedPos - transform.position).normalized * adjustedAccel;
			Debug.Log("speed up");

In my mind this seems like it should work, however, it clearly doesn’t. it has an tendency to overshoot, then head back, overshoot a lot (1/4 of stating distance ish) again, and repeat.

It does have to use that Velocity variable because other things will be effecting it later on.

Thank you, for all the help!

vectors cant be perfect. the slower you go the closer you’ll get but at a certain point you need to either accept being “close enough” or if you want exact positioning you need to get very very close and teleport there.

use mathf.approximate to make sure your either “close enough” or close enough to teleport.


teleport or stop and accept it as good enough