Skip to content

Instantly share code, notes, and snippets.

@farukaf
Last active October 14, 2020 12:19
Show Gist options
  • Save farukaf/6e3a5b7eb23c0e4d0fae74c4cc260a4b to your computer and use it in GitHub Desktop.
Save farukaf/6e3a5b7eb23c0e4d0fae74c4cc260a4b to your computer and use it in GitHub Desktop.
Calculate Distance Between Two Points in Three Dimensions C#
class Program
{
static void Main(string[] args)
{
var p1 = new Vector3()
{
X = 6,
Y = 4,
Z = -3
};
var p2 = new Vector3()
{
X = 2,
Y = -8,
Z = 3
};
Console.WriteLine(Vector3.Distance(p1, p2));
Console.Read();
}
}
public class Vector3
{
public double X { get; set; } = 0;
public double Y { get; set; } = 0;
public double Z { get; set; } = 0;
public static double Distance(Vector3 p1, Vector3 p2)
{
if (p1 == null)
{
throw new ArgumentException(nameof(p1), "Point can't be null");
}
if (p2 == null)
{
throw new ArgumentException(nameof(p2), "Point can't be null");
}
var tmp = Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2) + Math.Pow(p2.Z - p1.Z, 2);
return Math.Sqrt(tmp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment