2. Maths Pythagoras Theorem

Pythagoras’ Theorem

Most people who have done maths in high school, would have heard of Pythagoras’ theorem.

This is used to work out the unknown side of a right-angled triangle, if you know the other 2 sides.

Pythagoras Triangle

Here you can see the sides, A, B and C.

The Formula

Now Pythagoras’ theorem states that:

A^2 + B^2 = C^2

Where C is the hypotenuse – the long side opposite the right angle.

So if you know any two sides, you add them in, rearrange the formula if needed, and then you can solve for the unknown side.

If A and B are known:

C = sqrt(A^2 + B^2)

And if C and B are known:

A = sqrt(C^2 – B^2)

So How Would You Use This In A Game?

What about collision detection? Using this you can find the straight-line distance between two points in a 2 dimensional plane quite easily.

Take the difference between the two X positions as one short side of the triangle, and the difference between the two Y positions as the other:

dx = x2 – x1
dy = y2 – y1

Then:

distance = sqrt(dx^2 + dy^2)

So to put that in other words, we are finding the distance 🙂 If the distance is nothing, then the two points are located in the same position. If you are checking actual objects with a size, you normally compare that distance against the size/radius you are using for the collision instead.

The original version of this tutorial ended with me saying, “Not sure if that is right, sounds right from my position, although it is 1:18 am.” It turns out 1:18 am was doing me no favours there, so hopefully this explanation makes a little more sense!

Questions or corrections? If something doesn’t work or you spot something I’ve got wrong, leave a comment below. These tutorials have been around a long time, so useful corrections are always welcome!

  • March 25, 2010
  • 4