title: Calculating the speed of a moving object based on its distance to a target
body: <p>I am writing a simulation in which an object moves in a 2D world towards a target position, stored as vector <code>target(x,y)</code>. The object position is stored as position vector <code>pos(x,y)</code> as well. The object contains two more vectors, the desired movement velocity <code>dv(x,y)</code>, as well as the current movement velocity <code>cv(x,y)</code>. At the start of the simulation both these velocity vectors are initial, i.e. set to <code>(0,0)</code>.</p>
  
  <p>When the object should move towards the target position, I calcuate the desired velocity vector <code>dv</code>, normalize it, and scale it by a movement speed value:</p>
  
  <pre><code>dv.set(target).sub(pos).normalize()
  dv.scale(speed)
  </code></pre>
  
  <p>I want to make the movement look more realistic, that's why I use two velocity vectors. <code>dv</code> tells the full speed I want to move the object, and <code>cv</code> holds the real speed the object currently moves at.</p>
  
  <p>Then at each frame (update step) the current velocity <code>cv</code> is set based on the desired velocity <code>dv</code> and an acceleration value <code>acc</code>. This is done by simply calculating the difference between <code>cv</code> and <code>dv</code> and clamping this difference to <code>acc</code>. That way the object starts to move slowly and accelerates gradually to eventually reach full speed.</p>
  
  <p>So far this is working fine. Now I want to make use of <code>acc</code> for deceleration as well. When the distance between <code>pos</code> and <code>target</code> is at a certain value, the desired velocity <code>dv</code> should be set to <code>(0,0)</code>, so that the object gradually decelerates until it comes to a full stop at the target position.</p>
  
  <p>My question is: How can I calculate at which distance I need to set <code>dv</code> to <code>(0,0)</code> (i.e. tell the system to stop movement), so that the object decelerates correctly to stop <em>exactly</em> at the target position?</p>