- Home /
Any one know maths behind this MoveTowards() function ?
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
Answer by Bunny83 · Mar 11, 2013 at 04:57 PM
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;
}
How do you access this code? I'm pretty sure you are getting this code from the UnityEngine/UnityEditor DLL? But how do you open that DLL file?
$$anonymous$$aybe I am wrong, but whatever I try, I get a bunch of incomprehendable text when trying to open the DLLs.
Well, either with the Assembly browser that's integrated in $$anonymous$$onoDevelop (but it's poorly integrated and fails a lot), or use the open source tool ILSpy which is just another .NET-Reflector which supports C#, Visual Basic and, of course, IL (the intermediate assembly language).
Thanks @Bunny83 your answers really explains what happening inside the $$anonymous$$oveTowards() function.
I know this is super late, but in case you're still wondering, maxDelta is essentially the speed.
Answer by Statement · Mar 11, 2013 at 04:52 PM
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.
thanks for answering this my question @Statement :) i got it now.
Your answer
Follow this Question
Related Questions
Lerp bugging for- and backwards 2 Answers
Move Camera towards Object 1 Answer
Vector2.MoveTowards giving me a hard time 1 Answer
Camera moveTowards stuttering in place? 1 Answer
slow stop at position get from an httpRequest (www) 0 Answers