Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect touch in cocos2d?

I am developing a 2d game for iPhone by using cocos2d.

I use many small sprite (image) in my game. I want to touch two similar types of sprite(image) and then both sprite(image) will be hidden.

How can I detect touch in a specific sprite(image) ?

like image 626
Md Nasir Uddin Avatar asked Mar 12 '09 08:03

Md Nasir Uddin


People also ask

How do I download Cocos2d?

To download Cocos2d-x, go to http://www.Cocos2d-x.org/download and download Version 2.2. 3 from the website. Once downloaded, you can unzip the Cocos2d-x-2.2.


2 Answers

A better way to do this is to actually use the bounding box on the sprite itself (which is a CGRect). In this sample code, I put all my sprites in a NSMutableArray and I simple check if the sprite touch is in the bounding box. Make sure you turn on touch detection in the init. If you notice I also accept/reject touches on the layer by returning YES(if I use the touch) or NO(if I don't)

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event 
{
  CGPoint location = [self convertTouchToNodeSpace: touch];

  for (CCSprite *station in _objectList)
  {
    if (CGRectContainsPoint(station.boundingBox, location))
    {
      DLog(@"Found sprite");
      return YES;
    }
  }

  return NO;
}
like image 74
Terence Avatar answered Jan 20 '23 16:01

Terence


Following Jonas's instructions, and adding onto it a bit more ...

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
   UITouch* touch = [touches anyObject];
   CGPoint location = [[[Director sharedDirector] convertCoordinate: touch.location];
   CGRect particularSpriteRect = CGMakeRect(particularSprite.position.x, particularSprite.position.y, particularSprite.contentSize.width, particularSprite.contentSize.height);
   if(CGRectContainsPoint(particularSpriteRect, location)) {
     // particularSprite touched
     return kEventHandled;
   }
}

You may need to adjust the x/y a little to account for the 'centered positioning' in Cocos

like image 31
David Higgins Avatar answered Jan 20 '23 15:01

David Higgins