views:

231

answers:

1

Is it possible to do pixel perfect collision in a view based application ? I've been looking for example codes but with no luck... Also can you use colored bitmaps to represent collision for a certain color ?

+1  A: 

You can. It looks like it's easiest if you use a CGImage though.

You could create a 2D boolean array to read the pixel values to construct a hit grid (basically a 2x2 matrix) and then store that with your game object class.

You would need direct access to the pixel data for the CGImage (the code is here) then use a for loop, reading the pixel data into the array boolean values:

BOOL pixelGrid[xPixels][yPixels];
for (int i = 0; i < xPixels; i++) {
    for (int j = 0; j < yPixels; j++) {
        pixelGrid[i][j] = pixelIsOpaque(i, j);
    }
}

The method pixelIsOpaque() above, obviously doesn't exist, just replace with whatever the sample code gives you to extract the pixel value. You are storing whether a pixel exists (basically check if the pixel is opacity > 0)

Once you have this grid (generate it at the beginning of your program once and store the resultant 2D array inside the game object) then you need a collision detection method.

BOOL detectCollision( BOOL *pixelGrid1, BOOL *pixelGrid2 ) {
BOOL result = NO;  
    for (int i = 0; i < xPixels; i++) {
        for (int j = 0; j < yPixels; j++) {
            if ( pixelGrid1[i][j].opacity != 0 && pixelGrid2[i][j].opacity != 0] ) {
                result = YES; break;
            }

    }
}
return result;
}

I just wrote this code on the fly so i may not be 100% compilable but i hope it gives you the idea. You could easily modify this but instead of comparing against opacity, simply compare against pixel colour value again, see here for getting the raw colour data.

Brock Woolf