Thursday, January 29, 2009

Collision Maps

As with most people who first start out, I am basing my game on one of the platformer examples (number 3, to be specific). I ran into a problem though. Because of the style of my levels (and most levels, probably) I needed pixel perfect background-sprite collision. This would also simplify the task of making collision maps.

By default, the demo uses 'tile collisions', where it checks the tile (each tile is 8x8 pixels) at a certain point on the map (as defined by the user). The method of doing this is with the function GetTile, which is used as follows:

GetTile (x, y);

What this does is checks if there is a colour at that certain point on the map. If it finds a colour it returns 1 (true), else if there is nothing there (transparency/magneta/00FF00), it returns 0 (false).

How this works in the game is like so:

void DownCollision(void) 'void' is just declaring a function.. you will learn about this if you learn to code...
{
return GetTile(
     (mario.x>>8) the weird >>8 thing is called 'fixed point' once again, it comes with coding skill
     + 16, mario's x position, plus 16 pixels
     (mario.y>>8) + 32 same as above, but with his y position
                            ) 
}

Basically, this all comes down to:

void DownCollision(void)
{
     return GetTile((mario.x>>8) + 16, (mario.y>>8) + 32);
}

As you can probably see, this checks if there is something at mario's feet, smack-bang in the middle of the sprite. If there is, then GetTile returns 1, which then passes on the function, which then affects the function that actually stops mario if there is a collision:

if (DownCollision) mario.y -= 256; In the fixed point world, 256 equals 1 pixel!

This really just checks if mario is literally in the stage, as I explained before, and if he is, it moves mario up the screen a little.

All in all, it was actually surprisingly easy to get pixel-perfect collisions. All I needed to do was replace the GetTile function with PA_GetBgPixel, and I was all set. Of course, it's slightly more complicated than that, but only by 1 or 2 more letters :]