0
votes

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?

3
show your code, so some one can help youAyaz

3 Answers

1
votes

I've looked at the cocos2d-x source code.

It doesn't hit-test before sending the touch event to touch-delegate.
Hence you have to perform the hit-test yourself in the touchBegan.(At least for the targetedDelegate type)

1
votes

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;
0
votes

Override Touch Delegate:

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    BOOL shouldClaimTouch = NO;

    CGRect myRect = CGRectMake(0, 0, self.contentSize.width, self.contentSize.height);

    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    CGPoint absoluteTouch = CGPointMake(fabsf(touchLocation.x), fabsf(touchLocation.y));

    BOOL layerContainsPoint = CGRectContainsPoint(myRect, absoluteTouch);
    if( layerContainsPoint )
    {
        shouldClaimTouch = YES;
        NSLog(@"Sprite was touched!");
        [self fireEvent];
    }

    return shouldClaimTouch;
}