在接口声明后的HelloWorldLayer.h中创建一个score属性,如
@property (nonatomic, retain) int score;
然后在您的 .m 文件中将其合成到 @implementation HelloWorldLayer 行之后。
创建设置和获取分数的方法:
-(int)getScore {
return self.score;
}
-(void)setScore:(int)newScore {
self.score = newScore;
}
在init方法中,将属性的值设置为零,
if( (self=[super init] )) {
//... other stuff
[self setScore:0]
}
您可以使用 setScore 方法更新分数,但我建议为此使用另一种调用 setScore 的方法,以便您可以通过单行调用在不同的地方使用它,并进行任何更改,例如在某些情况下分配更多分数,比如半秒内的两次碰撞等。
-(void)updateScore:(int)increment {
int currentScore = [self getScore];
[self setScore:(currentScore + increment)];
}
同样,对于标签,
@property (nonatomic, retain) CCLabelTTF scoreLabel; // in header
和
@synthesize scoreLabel; // in .m file
同样,在您的 init 方法中,使用位置、层和初始文本等初始化 label。然后您可以在 updateScore 方法中更新该文本。
-(void)updateScore:(int)increment {
int currentScore = [self getScore];
[self setScore:(currentScore + increment)];
[scoreLabel setString:[NSString stringWithFormat:@"Score: %i", [self getScore]]];
}
在继续之前,请务必通读tutorial,以避免对常见任务造成混淆。