Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a Score Integer updated and displayed in Cocos2d?

I am obviously making a game that has a score. How do I call an update method and have the integer actually displayed in the Top-Right corner?

like image 505
skippy_winks Avatar asked Apr 10 '11 11:04

skippy_winks


2 Answers

Here, this might 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]; whenever the user kills an enemy.

That should work, tell me if it didn't because I have not tested it.

like image 63
tallen11 Avatar answered Nov 15 '22 17:11

tallen11


in header file:

@interface GameLayer : CCLayer
{
    CCLabelTTF *_scoreLabel;
}

-(void) updateScore:(int) newScore;

in 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 don't want to use an 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 the score very frequently.

Also read the cocos2d programming guide about labels.

like image 26
Felix Avatar answered Nov 15 '22 17:11

Felix