views:

282

answers:

1

How to tell if you touched a CCLabel?

The following code obviously does not work well enough because it only tests for point equality. Naturally touch point will not necessarily be equal to the position property of the CCLabel (CCNode). How to I tell if a Touch point has fallen within the "rectangle?" of the CCLabel?

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 for( UITouch *touch in touches ) {
  CGPoint location = [touch locationInView: [touch view]];

  location = [[CCDirector sharedDirector] convertToGL:location];

  self.myGraphManager.isSliding = NO;

  if(CGPointEqualToPoint(location, label1.position)){

   NSLog(@"Label 1 Touched");

  }else if(CGPointEqualToPoint(location, label2.position)){

   NSLog(@"Label 2 Touched");

  }else if(CGPointEqualToPoint(location, label3.position)){

   NSLog(@"Label 3 Touched");

  }else if(CGPointEqualToPoint(location, label4.position)){

   NSLog(@"Label 4 Touched");

  }else if(CGPointEqualToPoint(location, label5.position)){

   NSLog(@"Label 5 Touched");

  }else if(CGPointEqualToPoint(location, label6.position)){

   NSLog(@"Label 6 Touched");

  }

 }
}
+1  A: 

Use the bounding box of the CCLabel and test if the point is contained in the rect using Apple's CGRectContainsPoint method as described here: http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectContainsPoint

To get the bounding box of the CCLabel follow this advice on my cocos2d FAQ, how to get a sprite's bounding box rectangle: http://www.learn-cocos2d.com/knowledge-base/cocos2d-iphone-faq/learn-cocos2d-public-content/manual/cocos2d-general/14813-how-to-get-a-sprites-bounding-box-bounding-rectangle-with-code

It will add an Objective-C category to CCSprite so it will behave like a CCSprite member method. Since CCLabel is a subclass of CCSprite this will work too. You call it like this:

CGRect bbox = [label getBoundingRect];
GamingHorror