Таймер обратного отсчета в cocos2d? - PullRequest
1 голос
/ 07 марта 2011

Я пытаюсь создать таймер обратного отсчета в 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 ]

4 голосов
/ 07 марта 2011

Ваш int countTime = 20; объявляет себя каждый раз равным 20. Кроме того, ваш цикл while будет уменьшать countTimer так быстро, как система сможет обновить CCLabel. Если вы пытаетесь создать реальный таймер, вы хотите, чтобы он уменьшался ТОЛЬКО при вызове countDown:. Не во время цикла.

Попробуйте это:

@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 
0 голосов
/ 07 марта 2011

Ваш счет всегда становится 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];

Тогда вместо использования CCLabel вы должны использовать CCLabelBMFont. Это намного быстрее:)

...