夏までにiPhone アプリつくってみっか!

趣味でiPhone/Androidアプリを開発し、日々勉強した事を書いています。オープンワールド系レースゲームをUnityで開発中です。

【cocos2d】スコアを表示してみた

スコア表示を管理するクラスを作成しました。
CCLayerを継承し、CCLabelTTFで現在のスコアをハイスコアを表示します。今のところはゲームオーバーがないので常にスコア=ハイスコアの表示になっています。

実装はこんな感じです。
今回のハマりポイントはラベルのanchorPointの設定でした。_scoreLabel(右側)はラベルの右上をアンカーポイントに設定し画面右上角から10ピクセル左下にオフセット、_highScoreLabelは逆に左上をアンカーポイントにして画面左上角からのオフセットで位置決めしています。
ここで、アンカーポイントは0.0〜1.0の値で指定しなければならないのですが、私は間違えてわざわざピクセル数で指定してしまい、ラベルが遥か彼方へ行ってしまいました。当然画面には何も映りません。
cocos2dのクラスリファレンスを読んで間違いに気づきましたが、この手の思い込みによるバグはソースコードをどんなも読み返しても見つけられませんね。

#import "InfoLayer.h"


@implementation InfoLayer
{
    unsigned int _score;
    unsigned int _highScore;
    CCLabelTTF* _scoreLabel;
    CCLabelTTF* _highScoreLabel;
}

+ (InfoLayer *)sharedInfo
{
    static InfoLayer* sharedInstance = nil;
    if (sharedInstance == nil) {
        sharedInstance = [[self alloc] init];
    }
    return sharedInstance;
}

- (id)init
{
    if ((self = [super init])) {
        _score = 0;
        _highScore = 0;
        NSString* scoreString = [NSString stringWithFormat:@"%07d", _score];
        NSString* highScoreString = [NSString stringWithFormat:@"%07d", _highScore];
        _scoreLabel = [CCLabelTTF labelWithString:scoreString fontName:@"arial" fontSize:24];
        _highScoreLabel = [CCLabelTTF labelWithString:highScoreString fontName:@"arial" fontSize:24];
        [self addChild:_scoreLabel];
        [self addChild:_highScoreLabel];
        _scoreLabel.anchorPoint = ccp(1.0, 1.0); //anchorPointは0.0 〜 1.0で指定!!
        _highScoreLabel.anchorPoint = ccp(0.0, 1.0);
        CGPoint scoreOffset = ccp(-10, -10);
        CGPoint highScoreOffset = ccp(10, -10);
        CGSize winSize = [CCDirector sharedDirector].winSize;
        CGPoint topRight = ccp(winSize.width, winSize.height);
        CGPoint topLeft = ccp(0, winSize.height);
        _scoreLabel.position = ccpAdd(topRight, scoreOffset);
        _highScoreLabel.position = ccpAdd(topLeft, highScoreOffset);
    }
    return self;
}

- (void)setScore:(unsigned int)score
{
    _score = score;
    [_scoreLabel setString:[NSString stringWithFormat:@"%07d", _score]];
    if (_score > _highScore) {
        _highScore = _score;
        [_highScoreLabel setString:[NSString stringWithFormat:@"%07d", _highScore]];
    }
}

@end

プロパティとしてはscoreだけを公開しています。
そのセッターメソッドを上書きして、画面表示の更新とハイスコアの処理を入れました。
実は、初めのバージョンではupdateメソッドでラベルの文字を更新していましたが、セッターメソッドで必要なときだけ更新すれば良い事に気づき少しだけ無駄が省けました。
今は味気ないarialフォントの白文字ですが、リリースまでにはビットマップフォントに変える予定です。