Objective-c – How to detect touch in cocos2d

cocos2d-iphoneiphoneobjective c

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) ?

Best Answer

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;