DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 5.13 Calculating the Distance Between Two Points

5.13.1 Problem

You want to calculate the distance between two points.

5.13.2 Solution

Create custom Math.getDistance( ) method.

5.13.3 Discussion

You can calculate the distance (in a straight line) from any two points by using the Pythagorean theorem. The Pythagorean theorem states that in any right triangle (a triangle in which one of the angles is 90 degrees), the length of the hypotenuse (the long side) is equal to the square root of the sum of the squares of the two other sides (referred to as the legs of the triangle). The Pythagorean theorem is usually written as:

a2 + b2 = c2

You can use this formula to calculate the distance between any two points, where a is the difference between the points' x coordinates, b is the difference between their y coordinates, and c (the distance to be determined) equals the square root of (a2 + b2). In ActionScript, this is written as:

var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));

How do you calculate the distance between two points using a right triangle? While it might not seem immediately obvious, you can form an imaginary right triangle using any two points in the Flash coordinate system, as shown in Figure 5-1.

Figure 5-1. The hypotenuse of a right triangle is drawn between two points to calculate the distance between the points
figs/ascb_0501.gif

The hypotenuse of the imaginary triangle is formed by the line connecting the two points. The legs of the triangle are formed by lines extending horizontally and vertically from the two points. You can find the lengths of the legs by finding the differences between the x and y coordinates. The length of leg a is determined by the difference in the points' x coordinates, and the length of leg b is determined by the difference in the points' y coordinates. Once you know the lengths of legs a and b, you can use the Pythagorean theorem to calculate the length of the hypotenuse, c, which represents the distance between the points (our original quarry).

It is convenient to encapsulate this calculation in a method that you can reuse. The custom Math.getDistance( ) method we define here accepts the x and y coordinates of the two points as its four parameters:

Math.getDistance = function (x0, y0, x1, y1) {

  // Calculate the lengths of the legs of the right triangle.
  var dx = x1 - x0;
  var dy = y1 - y0;

  // Find the sum of the squares of the legs of the triangle.
  var sqr = Math.pow(dx, 2) + Math.pow(dy, 2);

  // Return the square root of the sqr value.
  return (Math.sqrt(sqr));
};

Here is an example of the Math.getDistance( ) method being used to calculate the distance between two points at (300,400) and (0,0):

trace(Math.getDistance(300, 400, 0, 0));  // Displays: 500

5.13.4 See Also

Recipe 4.7

    [ Team LiB ] Previous Section Next Section