Ignore Y axis difference in vector3.distance + calc execution time ?

Hello peoples,

In my game I use Vector3.distance() a lot to calculate the distance between 2 object.

The problem is I want to ignore the Y axis difference, as if I was calculating the distance in a 2D world.

Actually I do something like that :

Vector3 object1Pos = object1Transform.position;
Vector3 object2Pos = object2Transform.position;
object1Pos.y = 0f;
object2Pos.y = 0f;
float distance = Vector3.Distance (object1Pos, object2Pos);

Is their a function to do that faster ?

private float vector2DDistance (Vector3 v1, Vector3 v2)
{
    return (Mathf.Sqrt (Mathf.Pow (Mathf.Abs (v1.x - v2.x), 2f) + Mathf.Pow (Mathf.Abs (v1.z - v2.z), 2f)));
}

Damn pythagore I forgot about this good guy :slight_smile:

Is their any way to know the calculation time ?

This may be marginally faster, as it uses fewer function calls:

private float vector2DDistance (Vector3 v1, Vector3 v2)
{
    float xDiff = v1.x - v2.x;
    float zDiff = v1.z - v2.z;
    return Mathf.Sqrt((xDiff * xDiff) + (zDiff * zDiff));
}

Regarding calculation time, use the profiler.

1 Like

Thanks for your answer