开发者

How to get the location (x,y) of a CCLabel that is a child of a CCScene?

(learning Cocos2D)

After creating a CCLabel and adding it to a CCLayer like this:

//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 th开发者_如何转开发e screen?


First you need to register your scene to receive touch events. So set self.isTouchEnabled = YES in the scene's -(id)init method. 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.

- (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.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜