I’m just learning Cocos2d and Objective-C, and I have some problems with touch detection.
I have several sprites in HelloWorldLayer and some draggableSprites (NSMutableArray). Two of the draggableSprites are located one over another (the bottom one is bigger).
Then i have some code that shakes a touched sprite:
- (void)selectSpriteForTouch:(CGPoint)touchLocation {
CCSprite *touchSprite = nil;
for (CCSprite *sprite in dragableSprites) {
if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
touchSprite = sprite;
break;
}
}
if (touchSprite != selSprite) {
[selSprite stopAllActions];
[selSprite runAction:[CCRotateTo actionWithDuration:0.1 angle:0]];
CCRotateTo * rotLeft = [CCRotateBy actionWithDuration:0.1 angle:-1.0];
CCRotateTo * rotCenter = [CCRotateBy actionWithDuration:0.1 angle:0.0];
CCRotateTo * rotRight = [CCRotateBy actionWithDuration:0.1 angle:1.0];
CCSequence * rotSeq = [CCSequence actions:rotLeft, rotCenter, rotRight, rotCenter, nil];
[touchSprite runAction:[CCRepeatForever actionWithAction:rotSeq]];
selSprite = touchSprite;
}
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
[self selectSpriteForTouch:touchLocation];
return TRUE;
}
But when I touch the top or bottom sprites, only bottom one is shaking (it was added first in init).
I think that I need to replace the code CGRectContainsPoint(sprite.boundingBox, touchLocation), but I just don’t know how.
I spent several nights on forums but I still can’t understand how to make the top sprite shake…
Try something more like this (notice it is
ccTouchesBegannotccTouchBegan):The way the for loop is set up in
selectSpriteForTouchwill cause only the first object indraggableSpritesto be selected, because of yourbreakstatement. With this new code, each sprite whose bounding box contains the touch will be animated. The code might not be perfect because I typed it straight into Chrome, but you get the idea.Another important thing to note is that you cannot run the same action on two different sprites, like this:
This code will not work as intended; only the last sprite(
oneMoreSprite) will be animated. In order to re-use CC animations with multiple sprites, use this code:We make a copy of the action so it can be run by another sprite (
someOtherSprite,oneMoreSprite) without removing it from the original sprite,someSprite. Then, we autorelease it so we don’t have a memory leak.