如何判断您是否触及过CCLabel?

时间:2010-05-23 06:27:41

标签: iphone xcode opengl-es cocos2d-iphone

如何判断您是否触摸过CCLabel?

以下代码显然效果不佳,因为它只测试点相等性。自然触摸点不一定等于CCLabel(CCNode)的位置属性。如何判断Touch点是否落入“矩形”? 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 个答案:

答案 0 :(得分:3)

使用CCLabel的边界框并使用Apple的CGRectContainsPoint方法测试该点是否包含在rect中:http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectContainsPoint

要获取CCLabel的边界框,请在我的cocos2d常见问题解答中遵循以下建议:如何获取精灵的边界框矩形: 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

它会向CCSprite添加一个Objective-C类别,因此它的行为类似于CCSprite成员方法。由于CCLabel是CCSprite的子类,因此也可以使用。你这样称呼它:

CGRect bbox = [label getBoundingRect];