1

我正在尝试在 cocos2d 中创建一个倒数计时器,但我无法帮助并想解决这个问题,我的代码低于此,也许逻辑错误但我无法修复。

-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init] )) {


    CCSprite *background = [CCSprite spriteWithFile:@"backgame.png"];
    CGSize size = [[CCDirector sharedDirector] winSize];
    [background setPosition:ccp(size.width/2, size.height/2)];

    [self addChild: background];


    [self schedule:@selector(countDown:)];              
}
return self;
}

-(void)countDown:(ccTime)delta
{

CCLabel *text = [CCLabel labelWithString:@" " 
                                         fontName:@"BallsoOnTheRampage" fontSize:46];

text.position = ccp(160,455);
text.color = ccYELLOW;
[self addChild:text];

int countTime = 20;
while (countTime != 0) {
    countTime -= 1;
    [text setString:[NSString stringWithFormat:@"%i", countTime]];
} 

} 
4

2 回答 2

4

int countTime = 20;每次都声明自己为 20。此外,您的 while 循环将尽可能快地减少 countTimer,因为系统可以更新 CCLabel。如果您尝试做一个真正的计时器,您希望它仅在countDown:被调用时递减。不是在while循环期间。

试试这个:

@interface MyScene : CCLayer
{
   CCLabel *_text;

}

@property (nonatomic, retain) int countTime;

@end

@implementation MyScene

@synthesize countTime = _countTime;

-(id) init {
    if( (self=[super init] )) {


    CCSprite *background = [CCSprite spriteWithFile:@"backgame.png"];
    CGSize size = [[CCDirector sharedDirector] winSize];
    [background setPosition:ccp(size.width/2, size.height/2)];

    [self addChild: background];
    _countTime = 20;

    _text = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", self.countTime] 
                                         fontName:@"BallsoOnTheRampage" fontSize:46];

    text.position = ccp(160,455);
    text.color = ccYELLOW;
    [self addChild:_text];

    [self schedule:@selector(countDown:) interval:0.5f];// 0.5second intervals



    }
return self;
}

-(void)countDown:(ccTime)delta {

   self.countTime--;
  [_text setString:[NSString stringWithFormat:@"%i", self.countTime]];
  if (self.countTime <= 0) {

    [self unschedule:@selector(countDown:)];
  }
}

@end 
于 2011-03-07T18:19:05.897 回答
-1

在您的倒计时中,您的计数始终变为 20。

您还应该将其移至您的 init:

CCLabel *text = [CCLabel labelWithString:@" " 
                                     fontName:@"BallsoOnTheRampage" fontSize:46];

text.position = ccp(160,455); text.color = ccYELLOW; [自我添加孩子:文本];

然后你应该使用:

[self schedule:@selector(countDown:) interval:1.0f];

然后,您应该使用 CCLabelBMFont 而不是使用 CCLabel。它要快得多:)

于 2011-03-07T18:22:15.587 回答