Recipe 4.13. Calculating the Distance Between Two Points


Problem

You want to calculate the distance between two points.

Solution

Use Math.pow( ) and Math.sqrt( ) in conjunction with the Pythagorean theorem.

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 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 (a 2 + b 2). In ActionScript, this is written as:

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

How do you calculate the distance between two points using a right triangle? Although 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 4-1.

Figure 4-1. The hypotenuse of a right triangle is drawn between two points to calculate the distance between the points


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 query).




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net