Fernando D'Andrea
Fernando D'Andrea

Reputation: 307

Most efficient way to calculate the distance between 2 integer coordinate points?

I have two tridimensional coordinates stored as six int values. What is the more efficient way of calculating the float distance between the described locations:

  1. Vector3.distance( new Vector3( (float) a, (float) b, (float) c), new Vector3 ( (float) x, (float) y, (float) z)) ;
  2. Implement the proper math in a function taking the integers as parameters and doing all casts to float, all ^2, and the square root in plain c#?

Upvotes: 1

Views: 3133

Answers (1)

user2299169
user2299169

Reputation:

#1: There's a function for that in Unity: Vector3.Distance, as you already added. This is the most efficient way (the only better option would be to get float values instead of ints at the first place).
#2: //unity private Vector3 Int2Vector3 (int x, int y, int z) { return new Vector3 ((float)Mathf.Sqrt(x), (float)Math.Sqrt(y), (float)Math.Sqrt(z)); } //plain c# private float Int2FloatSqrt (int a) { return (float)Math.Sqrt(a); }

EDIT: Here's Unity's .Distance function for a better understand:
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); }

Upvotes: 2

Related Questions