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.

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!
Hi Flekken,
That is exactly true, A^2 + B^2 will only equal 0 if A and B is 0.
While the formula you have given is the true formula for working out the distance between two points, look at what it is actually doing. I will look at 2D space:
Now if we have a collision when the result is 0, if we apply some basic maths to the distance formula, we can remove the sqrt:
0 = sqrt((x2-x1)^2 + (y2-y1)^2)
0^2 = sqrt((x2 – x1)^2 + (y2 – y1)^2)^2
0 = (x2 – x1)^2 + (y2 – y1)^2
And now look at what x2-x1 and y2-y1 do. They give us the length of the line segments A and B.
Therefore:
x2 – x1 = A and y2 – y1 = B
And then:
0 = (A)^2 + (B)^2
0 = A^2 + B^2
Therefore we have a collision. Both this shorthand version and the full version of the distance formula are the same thing.
Hope this helps clarify 🙂
Swiftless
I don’t understand how can you use this for calculating distance. The only time A^2 + B^2 would be 0 is when A and B is 0. The proper formula for calculating distance between 2 point is:
sqrt( (x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2 )
What if A = 1 and B = i ???
Hey Dan,
Then I would have to ask why are you using imaginary numbers as lengths?
Cheers,
Swiftless