Search code examples
algorithmkinematics

Calculating the speed of a moving object based on its distance to a target


I am writing a simulation in which an object moves in a 2D world towards a target position, stored as vector target(x,y). The object position is stored as position vector pos(x,y) as well. The object contains two more vectors, the desired movement velocity dv(x,y), as well as the current movement velocity cv(x,y). At the start of the simulation both these velocity vectors are initial, i.e. set to (0,0).

When the object should move towards the target position, I calcuate the desired velocity vector dv, normalize it, and scale it by a movement speed value:

dv.set(target).sub(pos).normalize()
dv.scale(speed)

I want to make the movement look more realistic, that's why I use two velocity vectors. dv tells the full speed I want to move the object, and cv holds the real speed the object currently moves at.

Then at each frame (update step) the current velocity cv is set based on the desired velocity dv and an acceleration value acc. This is done by simply calculating the difference between cv and dv and clamping this difference to acc. That way the object starts to move slowly and accelerates gradually to eventually reach full speed.

So far this is working fine. Now I want to make use of acc for deceleration as well. When the distance between pos and target is at a certain value, the desired velocity dv should be set to (0,0), so that the object gradually decelerates until it comes to a full stop at the target position.

My question is: How can I calculate at which distance I need to set dv to (0,0) (i.e. tell the system to stop movement), so that the object decelerates correctly to stop exactly at the target position?


Solution

  • Use the kinematic equations:

    vf2 = vi2 + 2 * a * d

    • vf is your final velocity, or 0 (the speed you want to be going)

    • vi is your initial velocity, given (the speed your object is currently moving).

    • a is acceleration

    • d is distance.

    Solve for d:

    • 2*a*d = vf2 - vi2

    • 2*a*d = 0 - vi2

    assume acceleration is negative, so multiply both sides by -1

    • 2*|a|*d = vi2

    |a| is the absolute value of your acceleration (deceleration in your case)

    • d = vi2 / (2*|a|)