Hi guys

any one know, how this MoveTowards() function works ? whats the maths behind this function ?

I was trying to create a function to move my character from current position to a target position in X,Y plane, Let me tell you i am not good in maths. And than i found this function which does the same thing cheers. but i would love to know the maths behind this function.

So, Please help me understand whats happening in this MoveTowards() function.

thanks

This is the actual code behind the function

```
// Vector3.MoveTowards
public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta)
{
Vector3 a = target - current;
float magnitude = a.magnitude;
if (magnitude <= maxDistanceDelta || magnitude == 0f)
{
return target;
}
return current + a / magnitude * maxDistanceDelta;
}
```

Just in case you didn’t ment Vector3.MoveTowards, here’s Mathf.MoveTowards:

```
// Mathf.MoveTowards
public static float MoveTowards(float current, float target, float maxDelta)
{
if (Mathf.Abs(target - current) <= maxDelta)
{
return target;
}
return current + Mathf.Sign(target - current) * maxDelta;
}
```

The basic calculation is:

```
newPos = startPos + (endPos - startPos).normalized * maxDist;
```

If you want it to go no further than the endPos, you will need to clamp the distance you use.

It figures out the direction you are moving towards, and adds direction * maxDistanceDelta. If the remaining distance is less than maxDistanceDelta, then it simply returns the target.

```
if (remainingDistance <= maxDistanceDelta)
return target;
else
return current + directionToTarget * maxDistanceDelta;
```

That’s pretty much how it works.