What is the correct way to implement hit detection with non-rectangular sprites?

Posted by hogni89 on Game Development See other posts from Game Development or by hogni89
Published on 2012-09-19T20:32:10Z Indexed on 2012/10/01 21:53 UTC
Read the original article Hit count: 215

Filed under:
|
|

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;
            break;
        }
    }
    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?

© Game Development or respective owner

Related posts about ios

Related posts about cocos2d