At first glance the Pythagorean Theorem doesn’t appear to relate to game development. But we’ll see in a bit that it does.

First though, let’s cover a bit of math. The Pythagorean Theorem states that for any right triangle, the sum of the squares of the two legs is equal to the square of the hypotenuse.

Don’t know about you, but pictures always help me. So let’s take a look at the triangle below.

Assuming that the angle between a and b is 90 degrees, the formula to find c, or the hypotenuse, is.

[latex]c^{2} = a^{2} + b^{2}[/latex]

or

[latex]c = \sqrt{a^{2} + b^{2}}[/latex]

## Example please!

The triangle above is a special case called a 3-4-5 triangle. It’s sides measure 3, 4, and 5. 3-4-5 is called a Pythagorean triple which is a when the 3 sides of a right triangle are integers.

Here is our triangle again, this time with some numbers.

Same triangle, scaled down a bit so you can see the squares on the outside.

In the example a=3, b=4, and c=5.

[latex]\begin{align}c^2 &= a^2 + b^2\\ 5^2 &= 3^2 + 4^2\\ 25 &= 9 + 16\\ 25 &= 25\end{align}[/latex]

Between the a and b sides there are 25 squares (9 + 16) and there are also 25 squares on the c side.

## Ok, so what about games?

Let’s say you’re making a pong game in ActionScript. How boring would it be if you could only move the ball horizontally or vertically? Not much of a game. You’d either put both paddles in the middle and watch the ball bounce back and forth or do nothing as the ball bounces up and down in the middle.

What you need is a way to make the ball move diagonally, but you can only change the x and y values. Take a look at the following code.

ball.y += 5; ball.x += 12;

How far does the ball move diagonally?

It’s moving 5 pixels vertically and 12 pixels horizontally. But since they’re happening at the same time it’s moving diagonally. Let’s use the Pythagorean Theorem to figure out how far it’s moving each frame.

Side a is 5, side b is 12.

[latex]\begin{align}c &= \sqrt {a^2 + b^2}\\ &= \sqrt{5^2 + 12^2}\\&= \sqrt{25 + 144}\\&= \sqrt {169}\\ c &= 13\end{align}[/latex]

So our ball is moving 13 pixels diagonally each time. 5-12-13 is another Pythagorean Triple.

## Now what?

Real world, you’ll probably be doing it the other way around. You know the speed you want the ball to move, the hypotenuse, and have to figure out the x and y deltas. That takes a bit of trigonometry though and this post is getting long enough.

## Leave a Reply