如何判断您是否碰过CCLabel?
下面的代码显然不能很好地工作,因为它仅测试点相等性。自然,接触点不一定等于CCLabel(CCNode)的position属性。如何判断接触点是否落在“矩形”范围内? 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");
}
}
}
最佳答案
使用CCLabel的边界框,并使用Apple的CGRectContainsPoint方法测试点是否包含在矩形中,如下所述:http://developer.apple.com/mac/library/documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectContainsPoint
要获取CCLabel的边界框,请遵循我的cocos2d常见问题解答中的以下建议,即如何获取sprite的边界框矩形:
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];