Reputation: 41745
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?
Upvotes: 0
Views: 4011
Reputation: 8068
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;
}
Upvotes: 0
Reputation: 1377
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;
Upvotes: 1
Reputation: 41745
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)
Upvotes: 1