【问题标题】:Cocos2D scoring game [duplicate]Cocos2D计分游戏[重复]
【发布时间】:2012-08-16 08:21:32
【问题描述】:

可能重复:
Scoring System In Cocos2D

我收到了我之前提出的问题的答复,但我是编码新手,不知道该怎么做。回复如下:

"@synthesize 一个 int 类型的“score”属性和一个 CCLabelTTF 类型的“scoreLabel”属性。

在 -(void)init 中将你的 score 属性初始化为“0”

在第 126 行,将“score”属性加 1,并将该值设置为 CCLabelTTF。"

你能告诉我怎么做吗?请。链接到我的另一篇文章

--Scoring System In Cocos2D

【问题讨论】:

  • 你不应该发布这样的新问题,继续你的第一个问题的对话

标签: objective-c ios xcode sdk cocos2d-iphone


【解决方案1】:

当您合成一个私有变量(其他类看不到它)时,您允许其他类查看和/或修改该变量的值。

首先,你要创建变量:

NSMutableArray *_targets;
NSMutableArray *_projectiles;

int _score;
CCLabelTTF *_scoreLabel;

然后在你的init方法中将_score设置为0

-(id) init
{
    if( (self=[super init] )) {
        [self schedule:@selector(update:)];
        _score = 0;

然后将_score 变量递增(加1)并将_scoreLabel 的字符串(文本内容)设置为该值。

        if (CGRectIntersectsRect(projectileRect, targetRect)) {
            [targetsToDelete addObject:target];     
            _score++;
            [_scoreLabel setString:[NSString stringWithFormat:@"%d", _score]];                    
        }   

[_scoreLabel setString:[NSString stringWithFormat:@"%d", _score]]; 行是一种将_score 的整数转换为字符串(NSString)的方法。这是一种古老的 C 方式,%d 意味着将出现的任何内容都应显示为整数,而不是浮点数(有小数点)。

看起来您还需要“实例化”您的标签并将其作为子级添加到图层中。实例化只是创建某事物实例的一个花哨术语。将“类”视为椅子的蓝图,将“实例”视为根据该蓝图创建的椅子。一旦您创建了椅子(一个实例),您就可以对其进行修改(绘制、添加/移除腿等)。

因此,实例化您的标签并将其添加到层(本身):

-(id) init
{
    if( (self=[super init] )) {
        [self schedule:@selector(update:)];
        _score = 0;

        //Create label
        _scoreLabel = [CCLabelTTF labelWithString:@"0" fontName:@"Marker Felt" fontSize:16];

        //Add it to a layer (itself)
        [self addChild:_scoreLabel];

【讨论】:

  • 谢谢你太棒了!!
  • 没问题,我也忘记了 synthesize 变量。但是,KK 发布了一个很好的答案,老实说,他的答案更全面,是更好的长期解决方案。
【解决方案2】:

在接口声明后的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,以避免对常见任务造成混淆。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    相关资源
    最近更新 更多