【发布时间】:2011-04-10 11:01:19
【问题描述】:
我显然在制作一个有分数的游戏。如何调用更新方法并让整数实际显示在右上角?
【问题讨论】:
-
你希望它每秒更新一次还是类似的?
-
@allthewayapps 我希望每次用户杀死敌人时更新它。
标签: iphone xcode cocos2d-iphone
我显然在制作一个有分数的游戏。如何调用更新方法并让整数实际显示在右上角?
【问题讨论】:
标签: iphone xcode cocos2d-iphone
在这里,这可能有效
.h 文件中:
@interface HelloWorld : CCLayer {
int score;
CCLabelTTF *scoreLabel;
}
- (void)addPoint;
.m 文件中:
在init方法中:
//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];
其他地方:
- (void)addPoint
{
score = score + 1; //I think: score++; will also work.
[scoreLabel setString:[NSString stringWithFormat:@"%@", score]];
}
现在只需调用:[self addPoint];每当用户杀死敌人时。
应该可以,告诉我是不是不行,因为我还没有测试过。
【讨论】:
在头文件中:
@interface GameLayer : CCLayer
{
CCLabelTTF *_scoreLabel;
}
-(void) updateScore:(int) newScore;
在实现文件中:
-(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]];
}
编辑:如果不想使用 ivar,可以使用标签:
[self addChild:scoreLabel z:0 tag:kScoreLabel];
// ...
CCLabelTTF *scoreLabel = (CCLabelTTF*)[self getChildByTag:kScoreLabel];
编辑 2:出于性能原因,如果您非常频繁地更新分数,则应该切换到 CCLabelAtlas 或 CCBitmapFontAtlas。
【讨论】:
使用 UILabel
UILabel.text = [NSString stringWithFormat:@"%lu",score];
使用界面生成器将 UILabel 移动到视图顶部 您也可以通过编程方式创建它
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,500,30)];
[[self view] addSubview:label];
[label release]; // dont leak :)
【讨论】: