# Calculate movement in 2d

In 2d, I have a ship that I want to have move to specific coordinates. I've used Sidar's answer in How do I calculate how an object will move from one point to another? to get something that works allright, but it overshoots and at the end the ship just jumps around the destination. Basically the speed is 10, but the destination isn't a multiple of 10, so it can never be reached. What would be a good way to prevent that ?

Currently the function looks like that (sorry, Haskell, but it should be easy enough to understand) :

  let n = normalize \$ dest ^-^ cur in
let (V2 dx dy) = n ^* speed in
(curx + dx, cury + dy)


That's basically what's in Sidar's post, substract the destination coordinates with the current coordinates, normalize that, then multiply it by the speed and add that vector to the current coordinates to get the new ones. The question is : is there a way to prevent that from overshooting the destination, ideally without adding an if for each direction for x and y (that would be a bit ugly, but I don't see how else) ?

• Why not get the distance between the two points and simply slow down speed as you near it? – Sidar Dec 28 '17 at 17:02
• That would look nicer I think, but would make calculating interception points with orbitting planets a nightmare I think, so I just have a constant speed – Ulrar Dec 28 '17 at 17:44

I'm not 100% sure if this is what you mean, but a simple check on the remaining distance might be what you're looking for:

if ((dest - cur).length < speed)
{
cur = dest;
}
else
{
cur.x += dx;
cur.y += dy;
}


(Not Haskell but should be pretty easily readable). Essentially we check if we're "close enough" (meaning that we'd overshoot if we didn't adjust), and just position ourselves at the target if we are. Otherwise we just do the regular movement that you had already figured out.

• Well that was simple. I don't know why I didn't realise I didn't have to treat x and y separatly, this works fine, thanks ! – Ulrar Dec 28 '17 at 17:45