It’s a pretty common task to get the distance between 2 points. Maybe you’re wanting to see if two points are close enough to have collided. Maybe you’re making a golf game and the closer the ball is to the hole the higher the score. Either way, you need to know the distance.

## The Math

The math for this is related to the Pythagorean Theorem. You know, or can find, the differences between two x values and two y values. What you’re looking for is the hypotenuse of the right triangle formed by those legs.

Here’s the formula. We’ll talk in a bit.

[latex]\Huge \mbox{distance} = \sqrt{(x_2 – x_1)^2 + (y_2 – y_1)^2}[/latex]

This should look a lot like the formula Pythagorean Theorem, because it is. Distance is C, the difference between x1 and x2 is A, and the difference between y1 and y2 is B.

Everywhere I’ve seen this formula it’s always listed as x2 – x1 and y2 – y1. It really doesn’t matter though. Because you’re squaring the difference, it will always be a positive number so you don’t need to worry about which number is bigger.

## In Code

In the examples below we’re going to use helper variables just to keep it a bit cleaner.

#### ActionScript

var dX:int = x2 - x1; var dY:int = y2 - y1; var distance:Number = Math.sqrt(dX * dX + dY * dY);

ActionScript also has a Point class that does the math for you.

import flash.geom.Point; var p1:Point = new Point(0, 0); var p2:Point = new Point(100, 100); var dist:Number = Point.distance(p1, p2);

#### Java

int dX = x2 - x1; int dY = y2 - y1; double distance = Math.sqrt(dX * dX + dY * dY);

And like ActionScript, Java also has a Point class.

import java.awt.Point; Point p1 = new Point(0, 0); Point p2 = new Point(100, 100); double distance = p1.distance(p2);

The Java class also has a few more methods that will let you get the distance from a point to a specific X, Y value without creating a new Point reference and can get the distance squared as well if you need that.

#### Python

dX = x2 - x1 dY = y2 - y1 distance = math.sqrt(dX * dX + dY * dY)

## Other languages?

Pretty much any language that has a function to get the square root of a number will be able to get the distance between two points. Looking at the 3 languages listed above, the formula is the same for all 3. It’s just the commands that differ a bit.

## Be First to Comment