1. Maths Distance Formula

Distance Formula
The distance formula, like Pythagoras’ theorem, can be used for collision detection quite easily.
First off, you must know the points at which the objects are located.
Say object 1 is located at (x1, y1) and object 2 is located at (x2, y2), both on a 2 dimensional plane.

The 2D Distance Formula
Now I must clarify here that sqrt means the square root. There is no square root key on my keyboard, and in most programming languages you will see a square-root function called something like sqrt.
Ok, now the distance formula is:
D = sqrt((x2 – x1)^2 + (y2 – y1)^2)
Which expanded looks like:
D = sqrt((x2 – x1) * (x2 – x1) + (y2 – y1) * (y2 – y1))
Using It For Collision Detection
If we are comparing two points, they are in exactly the same position when D = 0. If our objects have some actual size, which they normally do unless we are making a game entirely out of mathematical dots, then we compare the distance against a collision distance instead.
For example, two circles with radii r1 and r2 overlap when their centre-to-centre distance is less than or equal to r1 + r2.
What About 3D?
But how would we do this in a 3D world you might be wondering.
Well don’t wonder any longer, it is almost the same. Instead of points at:
(x1, y1) and (x2, y2)
we simply add the z values, so they become:
(x1, y1, z1) and (x2, y2, z2)
Then we add the squared difference between the z values to the formula:
D = sqrt((x2 – x1)^2 + (y2 – y1)^2 + (z2 – z1)^2)
Which when expanded looks like:
D = sqrt((x2 – x1) * (x2 – x1) + (y2 – y1) * (y2 – y1) + (z2 – z1) * (z2 – z1))
And there we have it, we can calculate the distance between 2 points in either 2D or 3D space.
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!