- Home /
Best Way To Find Distance
What's the best way to find distance? These are the several methods I know:
distance = Vector3.Distance(transform.position, other.position);
distance = (transform.position - other.position).magnitude;
distance = Mathf.Sqrt((transform.position - other.position).sqrMagnitude);
I figure that Vector3.Distance()
is the slowest, but the other two involving magnitude are the ones in question. I know that .sqrMagnitude
is faster than .magnitude
, but if use Mathf.Sqrt()
, would that make it any faster or slower?
Now that being said, if Mathf.Sqrt()
is slower, than whats the best way to find the actual distance using .sqrMagnitude
?
Answer by Bunny83 · Jan 21, 2013 at 08:38 PM
This is Vector3.Distance:
// C#
public static float Distance(Vector3 a, Vector3 b)
{
Vector3 vector = new Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
return Mathf.Sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);
}
This is Vector3.sqrMagnitude:
// C#
public static float SqrMagnitude(Vector3 a)
{
return a.x * a.x + a.y * a.y + a.z * a.z;
}
This is Vector3.magnitude:
// C#
public static float Magnitude(Vector3 a)
{
return Mathf.Sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
}
And this is Mathf.Sqrt:
// C#
public static float Sqrt(float f)
{
return (float)Math.Sqrt((double)f);
}
As you can see they all do exactly the same in your cases.
ILSpy is your friend.
edit
It all depends on your case. For example if you need the real distance in units basically it doesn't matter which one you're using. However you can optimise things in certain cases. If you first need the distance and you know that you will need the normalized vector you can do this:
// C#
Vector3 dir = P2 - P1;
float length = dir.magnitude;
dir /= length;
Here you use only one Sqrt.
If you just need to compare distances (for sorting) you can omit the sqrt because the relation between the values will stay. That means if V1.magnitude is larger than V2.magnitude, then V1.sqrMagnitude will also be larger than V2.sqrMagnitude.
Answer by pietersmobile · Jul 11, 2014 at 11:51 AM
Another way is to estimate the magnitude without the use of a Sqrt: