【问题标题】:How to have a Score Integer updated and displayed in Cocos2d?如何在 Cocos2d 中更新和显示 Score Integer?
【发布时间】:2011-04-10 11:01:19
【问题描述】:

我显然在制作一个有分数的游戏。如何调用更新方法并让整数实际显示在右上角?

【问题讨论】:

  • 你希望它每秒更新一次还是类似的?
  • @allthewayapps 我希望每次用户杀死敌人时更新它。

标签: iphone xcode cocos2d-iphone


【解决方案1】:

在这里,这可能有效

.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];每当用户杀死敌人时。

应该可以,告诉我是不是不行,因为我还没有测试过。

【讨论】:

  • 再次感谢,我注意到您出现在我的一些问题中!并感谢您的帮助。现在看看我最近关于人工智能的问题。我真的可以在那里使用一些帮助。
  • @ipodfreak0313:哈哈。很高兴我能帮上忙! =) 我看了你的 AI 问题,但不幸的是我以前从未尝试过制作自己的 AI。不过我可能有一些想法。我会考虑一下,如果我有任何想法,请告诉你。
  • 谢谢大佬,我希望能为你解答一些问题,但我对 cocos2d 还是很陌生(好吧,也许不是新手,但我还有很多东西要学)。
【解决方案2】:

在头文件中:

@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:出于性能原因,如果您非常频繁地更新分数,则应该切换到 CCLabelAtlasCCBitmapFontAtlas

另请阅读cocos2d programming guide about labels

【讨论】:

  • 我是否必须安排调用函数 updateScore:(int)newScore 的更新?
【解决方案3】:

使用 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 :)

【讨论】:

  • @ipodfreak0313:不需要大写字母,UILabel 也适用于 Cocos2D,我的意思是,您也可以将内容渲染到 UIView 中,并且可以将其他内容添加到视图层次结构中。加:UIKits 的文本渲染比 Cocos2Ds 好很多。
  • @JustSid:我很确定建议不要在 cocos2d 场景之上渲染 UIKit 元素,但我可能错了。
  • @allthewayapps:有一些关于如何在 EAGLLayer 视图之上处理 UIViews 的一般提示/指南,但 Apple 制作了关于如何快速渲染以及如何在 3D 中渲染 UI 的自己的技术演示OpenGL ES 游戏,他们还使用了 UIKit(有关更多信息,请参阅 WWDC 2010 视频)。
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多