[英]How to get the location (x,y) of a CCLabel that is a child of a CCScene?
(learning Cocos2D) (学习Cocos2D)
After creating a CCLabel and adding it to a CCLayer like this: 创建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];
How do I determine when a user has TOUCHED the label on the screen? 如何确定用户何时触摸了屏幕上的标签?
First you need to register your scene to receive touch events. 首先,您需要注册场景以接收触摸事件。 So set
self.isTouchEnabled = YES
in the scene's -(id)init
method. 因此,在场景的
-(id)init
方法中设置self.isTouchEnabled = YES
。 Then add a method to the scene to register the touch dispatcher. 然后在场景中添加一个方法来注册触摸分配器。
- (void)registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
priority:0
swallowsTouches:YES];
}
The get the location from the UITouch
when the the scene gets a ccTouchBegan:withEvent:
message. 当场景获取
ccTouchBegan:withEvent:
消息时,从UITouch
获取位置。
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
}
Finally, you can test the touched location against the label's position by looking at the label's bounding box. 最后,您可以通过查看标签的边界框来针对标签的位置测试触摸的位置。
if (CGRectContainsPoint([label boundingBox], location)) {
// The label is being touched.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.