Collision detection (one of the coolest terms in all of game design), also known as hit-testing, is the process of determining whether two "objects" collide. In game development, it's a fundamental routine for many situations, such as when testing if a bullet hits an enemy or if the player reaches a wall.
On a two-dimensional map (which is probably the only thing you'll be working with in Axe), the simplest method of collision detection is simply a calculation of the distance between two objects to test. The x-positions of the two objects are compared, then the y. If they are close enough, the objects have collided.
When testing for a collision between object 1 of width
A and height
B at position (
X) and object 2 of width
C and height
D at position (
Y), possible code could look like the following:
This assumes that both objects are rectangular, and that the positions refer to the objects' top-left corner pixels. The first line tests if object 2 is not far enough away to the right of object 1 that there is no collision. As long as the x-position of object 2 is to the left of the pixel immediately to the right of object 1 (which would be the x-position of object 1, plus its width, or
V+A), the first conditional is true.
Similarly, the next three conditionals test if the two objects are within range on the left, top, and bottom. Think on the code for a bit until you understand it completely. You can play with the numbers in the script below to help you think; ignore the "test" codes for now.
If you understand how it works, we can make it smaller. Sure, the code I gave you above works, but why not optimize? To optimize these collisions, we'll take advantage of the fact that
< (unsigned less-than comparison) returns 1 if and only if the number to the left is less than the number to the right and greater than or equal to zero (assuming the number to the right is positive). In that case, we can compress that code above two lines at a time:
In the first line,
V+A is again the x-value of the pixel immediately to the right of object 1, and so
V+A-X-1 should be between 0 and the sum of the widths of the two objects minus one if there is a collision. The second row works the same way, but with the objects' y-positions.
If you understand all that, I applaud you. You don't have to understand all the details of how it works, so here's a little script to generate the code for you.
Width 1 (
Width 2 (
Height 1 (
Height 2 (
Note that while the diagram above only shows a collision between one set of corners, the code will test for all overlaps (collisions).