cocos2d中的倒数计时器?

时间:2011-03-07 17:59:30

标签: iphone ios timer cocos2d-iphone countdown

我正在尝试在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]];
} 

} 

2 个答案:

答案 0 :(得分:4)

你的int countTime = 20;每次都声明为20.此外,你的while循环会在系统可以更新CCLabel的速度下递减countTimer。如果您正在尝试执行一个真正的计时器,您希望它仅在调用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 

答案 1 :(得分:-1)

你的计数在你的countDown中总计变为20。

你也应该把它移到你的init:

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

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

然后你应该使用:

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

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