Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What is the correct way to implement hit or touch detection for non-rectangular sprites in Cocos2d?

I am working on a jigsaw puzzle, so our sprites have some strange forms (jigsaw puzzle bricks). As of now, we have implemented the "detection" this way:

- (void)selectSpriteForTouch:(CGPoint)touchLocation {  
    CCSprite * newSprite = nil;

    // Loop array of sprites
    for (CCSprite *sprite in movableSprites) {

        // Check if sprite is hit.
        // TODO: Swap if with something better.
        if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
            newSprite = sprite;
    if (newSprite != selSprite) {
        // Move along, nothing to see here
        // Not the problem

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    [self selectSpriteForTouch:touchLocation];
    return TRUE;

I know that the problem is in the keyword "sprite.boundingBox". Is there a better way of implementing this, or is it a limitation when using sprites based on .png's? If so, how should I proceed?

share|improve this question
up vote 5 down vote accepted

I actually found a simple solution!

Changed the character objects to not only include info and sprite, but also a CGPath. Then implemented a method, to loop all character objects, and check for

CGPathContainsPoint( params ...)

instead for

CGRectContainsPoint( params ...)

Tutorial I used: - "The magic of CGPath"

share|improve this answer

I'm unfamiliar with objective C, so I can't give any specific code. But the general way to accomplish things like this is by doing a per pixel collision check. Basically it works just like how you have it based on the rectangle, but before firing the touch event, you have to loop through all the pixels that were touched and make sure at least one of them wasn't transparent. That should help you get closer to the answer, hopefully someone else can give you some actual code samples on the subject.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.