Post
by **pgimeno** » Fri Nov 23, 2018 6:16 pm

Welcome to the forums!

Yes, this is expected. You can think about it in one dimension for simplicity. Your player starts at some distance from the target, and it will approach the target (the mouse cursor) in more or less constant steps. It's extremely unlikely that the last step lands exactly on the target; it's much more likely that in the step prior to reaching the target it lands closer than what it will advance in the next step, causing it to overshoot. Remember that dt is fractional and fluctuates somewhat randomly.

As for the fix. the best way is to detect whether it is overshooting, and when that happens, set it to the target coordinates instead. Overshooting can be detected by using some basic vector algebra: you calculate two vectors, the vector from the target to the prior position (the position before adding the xspeed/yspeed to the player's x/y), and the vector from the target to the next position (the position after adding the speed, or more properly the velocity, to the player's position). If these two vectors point in the same direction, that means you haven't overshot yet. If they point in opposite directions, you're overshooting. And if one of them has zero length, it means it's exactly at the target.

Now, the operation that tells you whether two vectors point in the same direction, is the dot product. The dot product of two vectors is a number, not a vector, and is calculated as the sum of the products of their components. So, if A and B are two 2D vectors, their dot product is A·B = Ax*Bx + Ay*By. The sign of that number, when calculated from the two vectors described above, will tell you whether you are overshooting in this step. If the dot product of these two vectors is positive, they point in the same direction, meaning you haven't overshot yet and you can still add the speed; if negative, they point in opposite directions and you're overshooting, therefore you have to correct the position; if zero, they are either perpendicular, or at least one of them is zero, so you're basically in the same case as overshooting, because you need to stop advancing too. I don't think you can get them perpendicular in this case, or maybe you can because of rounding errors, but that doesn't really matter.

With that, hopefully you can implement overshoot detection successfully to correctly land on the target.