The Pythagorean Theorem
Named after the Greek philosopher Pythagoras, the Pythagorean theorem states a simple but powerful relationship between the sides of a right triangle: The square of the hypotenuse of a right triangle is equal to the sum of the squares of the remaining two sides.
So, given a triangle with sides of length a, b, and c (where c is the hypotenuse), the theorem reads a2 + b2 = c2.
Now that you know (or have finally remembered!) this simple relationship, let's see how you can use it to find the distance between two points. Imagine that there is a black ball at the point (x1, y1) and a gray ball at the point (x2, y2). What is the distance between these balls?
You've probably guessed by now where I'm going with thisyou can use the Pythagorean theorem to find the distance between these two points. The only conceptual hurdle in this problem is to realize that there exists an imaginary right triangle whose hypotenuse is the line joining the two balls. But if you've been following along this far, that's probably not too big a hurdle.
The theorem states that c2 = a2 + b2. You'll recall that c is the hypotenusethat is, the value we're looking for to determine the distance between the two points. So we solve this equation for c to get If we write a and b in terms of the information we already know, then we can find the value of c. The side labeled a in the figure above is along the x axis, and its length is x2x1. Likewise, the length of side b is y2y1. Knowing this information, we can write a generic equation that will always give you the distance between any two points:
With this mathematical equation you can find the distance between any two points in Flash! This useful little "recipe" will come in handy frequently. For instance, you will use it when detecting most types of collisions in your games. In ActionScript this distance formula would look like this:
Distance=Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));