xcode 如何在 Cocos2d 中更新和显示分数整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5611294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to have a Score Integer updated and displayed in Cocos2d?
提问by Duncan
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?
我显然正在制作一款有分数的游戏。如何调用更新方法并使整数实际显示在右上角?
采纳答案by tallen11
Here, this might work
在这里,这可能有效
In the .h file:
在 .h 文件中:
@interface HelloWorld : CCLayer {
int score;
CCLabelTTF *scoreLabel;
}
- (void)addPoint;
In the .m file:
在 .m 文件中:
In the init method:
在 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];
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.
现在只需调用: [self addPoint]; 每当用户杀死敌人时。
That should work, tell me if it didn't because I have not tested it.
那应该有效,告诉我它是否无效,因为我还没有测试过它。
回答by Felix
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:
编辑:如果你不想使用 ivar,你可以使用标签:
[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.
编辑 2:出于性能原因,您应该切换到CCLabelAtlas
或者CCBitmapFontAtlas
如果您非常频繁地更新分数。
Also read the cocos2d programming guide about labels.
另请阅读有关标签的cocos2d 编程指南。
回答by Antwan van Houdt
Using UILabel
使用 UILabel
UILabel.text = [NSString stringWithFormat:@"%lu",score];
Move the UILabel in the top of the view using interface builder you could also create it programmatically
使用界面构建器将 UILabel 移动到视图顶部,您也可以通过编程方式创建它
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,500,30)];
[[self view] addSubview:label];
[label release]; // dont leak :)