2008-10-03

Mazegame solution

To day I was facing a classical problem. I wanted to build a classic maze game. The players task is to guide a charachter out of the maze with help of the arrowkeys on the keyboard .

The classic way to do this is to create MovieClips of all the walls in the level, add them to an array, then loop through the array to find if the charachter hits a wall with the hitTest function. This is a bit clumsy solution if the maze is complex with multiple walls or if I want to make many levels. I can't hitTest one single movieclip with the whole maze graphics in it, because the hitTest function tests the graphics boundingrectangle.

The solution I came up with was to check the colors around the charachter instead. So I just loaded a png image with transparent background and black lines as walls. Then I extracted the bitmapdata with bitmapdata.draw(mazeImage). After that I scanned the charachters boundingrectangle outlines for colors others then white with help of getPixel(x, y). To get the pixels around the charachter I made four loops, one loop for each side, like this one:

for(i=0; i<(player.width+1)/tolerance; i++)
{
xScan = player.x + (i*tolerance);
yScan = player.y;

controlHit(bitmapData.getPixel(xScan, yScan), xScan, yScan);
}

Then depending on where the pixel is found i bouncedback the charachter in the opposite direction.
To check if the charachter has reached the goal I just made the goal in a specifik color.

No comments: