Hello everybody.
I would like to implement a function to detect collisions between 2 sprites at pixel level. There is a good solution I've used before in ActionScript 3, but I need help to integrate it with cocos2d framework.
Original AS2 solution: http://gskinner.com/blog/archives/2005/08/flash_8_shape_b.html
Improved AS3 solution: http://troygilbert.com/2007/06/pixel-perfect-collision-detection-in-actionscript3/
Now look at this image:
![]()
Look at the third case: the method consist on drawing the first sprite in RED, the second in WHITE (with DIFFERENCE blending mode), and look if there is CYAN in the mix. We only draw the data inside the intersection, not the whole sprites.
The steps:
- Check for bounding box collision.
- Get the intersect rect.
- Create a bitmap object with the size of the intersection.
- Draw the sprite A in RED (taking into account scaling, rotation, etc) into the bitmap object.
- Draw the Sprite B in WHITE with DIFFERENCE blending (taking into account scaling, rotation, etc) into the same bitmap object.
- Look if there is CYAN color in the bitmap object.
I don't know how and where to draw the intersection data for both objects (steps 3, 4 and 5). Any ideas?
This is how the function could look:
-(BOOL) isCollisionBetweenSpriteA:(CCSprite*)spr1 spriteB:(CCSprite*)spr2 pixelPerfect:(BOOL)pp
{
BOOL isCollision = NO;
CGRect intersection = CGRectIntersection([spr1 boundingBox], [spr2 boundingBox]);
if (!CGRectIsEmpty(intersection))
{
// If we're not checking for pixel perfect collisions, return true
if (!pp) {return YES;}
// 1) Draw the Sprite 1 intersection content in RED color into a bitmap object (must check if it's rotated, scaled, etc)
// 2) Draw the Sprite 2 intersection content in WHITE color using DIFFERENCE blending option into the same bitmap object
// 3) Check if there is CYAN color in the mix (WHITE difference blended on RED makes CYAN)
}
return isCollision;
}
Please, any help and ideas to solve this will be very much appreciated. And maybe this function is a good feature for the cocos2d-iphone Extensions.
Regards.


