Arshad Parwez
Arshad Parwez

Reputation: 1563

How to add text on moving sprites in Cocos2D?

This is my first game in Cocos2D. I am using Cocos2D 1.0.1. I want to add text on moving sprites which should be center aligned. I've taken a CCLabelTTF with a text on it but I cannot make it center aligned. This is what I've done so far:-

-(void)addTarget {

int enType= arc4random() % 11;

CCSprite *target=[CCSprite spriteWithFile:[NSString stringWithFormat:@"balloon%d.png",enType] rect:CGRectMake(0, 0, 100, 119)];

label = [[CCLabelTTF alloc] initWithString:@"H!" dimensions:CGSizeMake([target contentSize].width, [target contentSize].height)  
                                 alignment:UITextAlignmentCenter fontName:@"verdana" fontSize:20.0f];

 label.color = ccc3(60,60,60);

[target addChild:label z: 10];

// Create the actions

id actionMove = [CCMoveTo actionWithDuration:rangeDuration position:ccp(actualX,winSize.height+target.contentSize.height)];

[target runAction:[CCSequence actions:actionMove, nil]];

//[label setPosition:target.position];


// Add to targets array 

[targets addObject:target];

}

Somewhere I've read that adding "[label setPosition:target.position];" in action of sprite will make it center aligned but in vain.

Upvotes: 2

Views: 2284

Answers (2)

Gabriel
Gabriel

Reputation: 3045

You don't need to change position of the label, everything is placed based on the center of the image. Also, with this

[target addChild:label z: 10];

try setting the button to z: 11, and keep the label at z:10

Upvotes: 0

James Webster
James Webster

Reputation: 32076

Try setting your label position here instead:

label = [[CCLabelTTF alloc] initWithString:@"H!" dimensions:CGSizeMake([target contentSize].width, [target contentSize].height)  
                                 alignment:UITextAlignmentCenter fontName:@"verdana" fontSize:20.0f];
//LABEL POSITION HERE
label.position = ccp(0, 40);
 label.color = ccc3(60,60,60);

You may have to play with the position values until you get it where you want.

Upvotes: 3

Related Questions