views:

109

answers:

1

(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 the screen?

A: 

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.
}
Frank Mitchell