[英]How to get the location (x,y) of a CCLabel that is a child of a CCScene?
(学习Cocos2D)
创建CCLabel并将其添加到CCLayer后,如下所示:
//From HelloWorldScene.m
// create and initialize a Label
CCLabel* label1 = [CCLabel labelWithString:@"Hello" fontName:@"Marker Felt" fontSize:10];
label1.position = ccp(35, 435);
// add the label as a child to this Layer
[self addChild: label1];
如何确定用户何时触摸了屏幕上的标签?
首先,您需要注册场景以接收触摸事件。 因此,在场景的-(id)init
方法中设置self.isTouchEnabled = YES
。 然后在场景中添加一个方法来注册触摸分配器。
- (void)registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
priority:0
swallowsTouches:YES];
}
当场景获取ccTouchBegan:withEvent:
消息时,从UITouch
获取位置。
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
}
最后,您可以通过查看标签的边界框来针对标签的位置测试触摸的位置。
if (CGRectContainsPoint([label boundingBox], location)) {
// The label is being touched.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.