Search code examples
cocos2d-iphonetouchccsprite

detecting touch for a sprite in cocos2d


I subclassed CCSprite to detect a touch to itself.

touchBegan fires upon touch, but log shows that the same sprite is handling touches all the time even though I am touching different sprites every time.
(It's pointer address is same for all touch.)

Further log shows that it's the last sprite I added to the world layer.

Why is the last sprite I added react to touch events all by itself?

I used CCSpriteBatchNode, would this be related to the problem?

Or is it because cocos2d just doesn't perform hit-test to find the correct object to deliver the touch event to?


Solution

  • You need to check if the location of the touch is inside the bounds of your sprite.

    Some weird pseudocode

    function touchBegan(UITouch touch, etc)
        CGPoint pos = get location of touch;
        if (CGRectContainsPoint(sprite.boundingBox, pos)) //I think that is the method you need. It's something like that.
            NSLog(@"Sprite was touched!");
            return YES;