Distance Formula in C#

Description: A simple function for calculating the distance between two points on a Cartesian Plane. Great for telling the distance of game sprites or objects traveling around in a 2D system.
Tested Platform: .NET 4.0, Visual Studio 2010, Windows 7
Language: C#
// Takes two sets of points and calculates the distance between them
// on a Cartesian coordinate system. 

public static double distance(int x1, int y1, int x2, int y2) {
     double xPoints = Math.Pow((x2 - x1), 2.0);
     double yPoints = Math.Pow((y2 - y1), 2.0);

     return Math.Sqrt(xPoints + yPoints);
}

Submitted: January 29, 2013

Return to the snippets listing