我如何在cocos2d中创造像《糖果粉碎传奇》那样的30分钟倒计时计时器?



朋友们,我需要每30分钟增加生命的倒计时计时器。所以我创建了一个倒计时计时器,但它只在那个调用上运行。这里我需要定时器全局运行。如果申请在后台或终止任何人帮助我。

这是我的代码

   int hours, minutes, seconds;
    NSTimer *timer;

- (void)updateCounter:(NSTimer *)theTimer {
if(secondsLeft > 0 ){
    secondsLeft -- ;
//        hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
//        myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours,     minutes, seconds];
    [self removeChild:Liveslable];
    Liveslable=[CCLabelTTF labelWithString:[NSString stringWithFormat:@"lives left in  %02d:%02d minuts",minutes, seconds] fontName:@"ArialMT" fontSize:25];
    Liveslable.position=ccp(winSize.width/2, winSize.height/2-140);
    [self addChild:Liveslable];
}
else{
    secondsLeft = 1800;
}
}
-(void)countdownTimer{
secondsLeft = hours = minutes = seconds = 0;
if([timer isValid])
{
    [timer release];
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
[pool release];
}

在这种情况下不适合使用NSTimer。您不能在后台执行代码,这是有充分理由的(想象一下,如果用户退出进程,或者关闭设备)。相反,您应该考虑存储一个生命被赋予的时间戳,然后计算下一个生命应该被赋予的时间戳。

你可以这样节省NSUserDefaults的时间:

float timeStamp = [[NSDate date] timeIntervalSince1970] * 1000; // Milliseconds 
[[NSUserDefaults standardUserDefaults] setFloat:timeStamp forKey:@"lastTimeStamp"];

并像这样检索前一个时间戳:

float lastTime = [[NSUserDefaults standardUserDefaults] floatForKey:@"lastTimeStamp"];

当用户打开应用程序时,你应该执行你的计算并相应地给予生命。这可以在applicationWillEnterForeground:AppDelegate.m中完成

您可以使用NSTimer来检查下一个时间戳是否与NSDate时间匹配,而应用程序正在运行

最新更新