What is the math behind Vector2.MoveTowards()?
Thanks in Advance!
/ Moves a point /current/ towards /target/.
public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta)
{
// avoid vector ops because current scripting backends are terrible at inlining
float toVector_x = target.x - current.x;
float toVector_y = target.y - current.y;
float sqDist = toVector_x * toVector_x + toVector_y * toVector_y;
if (sqDist == 0 || (maxDistanceDelta >= 0 && sqDist <= maxDistanceDelta * maxDistanceDelta))
return target;
float dist = (float)Math.Sqrt(sqDist);
return new Vector2(current.x + toVector_x / dist * maxDistanceDelta,
current.y + toVector_y / dist * maxDistanceDelta);
}
2 Likes
Thanks!