30 August 2017

Math – Calculate the distance between two points in 3D space

Always usefull in 3D development is a method to calculate the distance between two vectors. It's not very hard either, using the Pythagorean theorem. Here is how to do it in C# for two vectors, a and b:
public float Distance(Vector3 a, Vector3 b) =>
  (float)Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2) + Math.Pow(a.Z - b.Z, 2));