How to update and display an Integer in Cocos2d?

I obviously am making a game that has a rating. How to call the update method and display an integer in the upper right corner?

+8
iphone xcode cocos2d-iphone
source share
3 answers

Here it can work

In the .h file:

@interface HelloWorld : CCLayer { int score; CCLabelTTF *scoreLabel; } - (void)addPoint; 

In the .m file:

In the init method:

 //Set the score to zero. score = 0; //Create and add the score label as a child. scoreLabel = [CCLabelTTF labelWithString:@"8" fontName:@"Marker Felt" fontSize:24]; scoreLabel.position = ccp(240, 160); //Middle of the screen... [self addChild:scoreLabel z:1]; 

Somewhere else:

 - (void)addPoint { score = score + 1; //I think: score++; will also work. [scoreLabel setString:[NSString stringWithFormat:@"%@", score]]; } 

Now just call: [self addPoint]; when the user kills the enemy.

This should work, tell me if it is not, because I have not tested it.

+8
source share

in the header file:

 @interface GameLayer : CCLayer { CCLabelTTF *_scoreLabel; } -(void) updateScore:(int) newScore; 

in the implementation file:

 -(id) init { if( (self=[super init])) { // .. // add score label _scoreLabel = [CCLabelTTF labelWithString:@"0" dimensions:CGSizeMake(200,30) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:30]; [self addChild:_scoreLabel]; _scoreLabel.position = ccp( screenSize.width-100, screenSize.height-20); } return self; } -(void) updateScore:(int) newScore { [_scoreLabel setString: [NSString stringWithFormat:@"%d", newScore]]; } 

EDIT : if you do not want to use ivar, you can use tags:

 [self addChild:scoreLabel z:0 tag:kScoreLabel]; // ... CCLabelTTF *scoreLabel = (CCLabelTTF*)[self getChildByTag:kScoreLabel]; 

EDIT 2 . For performance reasons, you should switch to CCLabelAtlas or CCBitmapFontAtlas if you update your account very often.

Also read cocos2d shortcuts programming guide .

+3
source share

Using UILabel

 UILabel.text = [NSString stringWithFormat:@"%lu",score]; 

Move the UILabel to the top of the view using the interface builder, you can also create it programmatically

 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,500,30)]; [[self view] addSubview:label]; [label release]; // dont leak :) 
0
source share

All Articles