views:

161

answers:

2

I am programing a shooter game in cocos2d for the iphone. I and I want to exclude collision detection an the alpha of my sprite. How do I read the RGBA value of the single pixel. Thanks for the help.

A: 

Not specific to Cocos2d, but should work on any iPhone project -- check out this question & answer

Olie
+1  A: 

First off, think about if you really want to do this -- it's much more computationally expensive than other methods of collision detection (i.e, bounding box, circle collision) which may not be as accurate, but for most purposes work well enough.

If you really do want to do this, you should generate a mask for each of your sprites that you want to detect the collision between. This mask should ideally be a simple 1-bit representation of your sprite.

Next, for each sprite you want to check for a collision, you need to do a few steps:

  1. Since the pixel accurate collision is going to take a long time, do a bounding box collision first between the two sprites to see if you even need to check for pixel level collision.

  2. If you know the sprites have collided at the boundaries, calculate the rect of the collision. You may want to do an optimization at this stage that says if they are greater than X% overlapped that they have collided. Especially if your alpha areas of the sprite are along the outside edges.

  3. Using the rect area of the collision, go through the masks of each of your sprite -- if both pixels are 1, you have a collision -- exit out of the loop and do what you need to mark them as collided.

As you can see, this is very CPU heavy compared to the other methods, which is why I recommended against it at the beginning. Unless a system has hardware support for pixel accurate collisions (the Atari 2600 actually had this), most games are not going to use pixel values for their collisions.

If you decide to go with a bounding box approach, you can do things like shrinking the bounding box used for collisions to prevent false positives for when two sprites touch each other at a corner.

Good Luck!

Dennis Munsie