Identify which CCSprite is touched in Cocos2d

Posted by PeterK on Game Development See other posts from Game Development or by PeterK
Published on 2012-04-01T08:34:41Z Indexed on 2012/04/01 11:42 UTC
Read the original article Hit count: 328

I am trying to learn Cocos2d and is experimenting with Ray Wenderlich tutorial whack-a-mole: www.raywenderlich.com/2560/how-to-create-a-mole-whacking-game-with-cocos2d-part-1

In this tutorial three CCSprite's are popping up and you should click on them...

However, i am trying to identify which mole, rat in my case, is popping up and place a CCSprite above that. Initially this looked like an easy task but i am failing. I am trying to NSLog LEFT HIT. i would guess the problem is in the If-statement and the last "227" height parameter.

The left rat boundingBox = {{99.5, 146.5}, {165, 227}} (from NSLog).

The key code is in the ccTouchBegan function:

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { 

   CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
   for (CCSprite *rat in rats) {
       if (rat.userData == FALSE) continue;
       if (CGRectContainsPoint(rat.boundingBox, touchLocation)) {


          //left: rat boundingBox = {{99.5, 146.5}, {165, 227}}
          //mid: rat boundingBox = {{349.5, 146.5}, {165, 227}}
          //right: rat boundingBox = {{599.5, 146.5}, {165, 227}}



          //>>>>Here is where i try to get a hit<<<<
          if (CGRectContainsPoint(CGRectMake(99.5, 146.55, 165, 227), touchLocation)) {
              NSLog(@">>>>HIT LEFT<<<<<");
          }

I would really appreciate a few ideas how to get this to work.

© Game Development or respective owner

Related posts about cocos2d-iphone

Related posts about bounding-boxes