繁体   English   中英

倒数计时器iphone sdk?

[英]Countdown timer iphone sdk?

我在我的游戏中有一个倒数计时器,我正在试图弄清楚如何使它显示两个小数位并在我的表中显示2位小数。 现在它作为整数倒计时并记录为整数。 有任何想法吗?

-(void)updateTimerLabel{

     if(appDelegate.gameStateRunning == YES){

                            if(gameVarLevel==1){
       timeSeconds = 100;
       AllowResetTimer = NO;
       }
    timeSeconds--;
    timerLabel.text=[NSString stringWithFormat:@"Time: %d", timeSeconds];
}

    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];

要进行亚秒级更新,计时器的间隔需要<1。但是NSTimer的精度只有大约50 ms,因此scheduledTimerWithTimeInterval:0.01将不起作用。

此外,计时器可能会因各种活动而延迟,因此使用timeSeconds会导致计时不准确。 通常的方法是将NSDate现在与计时器启动的日期进行比较。 但是,由于此代码适用于游戏,因此当前的方法可能会减少对玩家的挫败感。 如果程序或后台进程消耗大量资源。


首先要做的是将countdownTimer转换为亚秒级间隔。

countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.67 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];

然后,不要按秒计算时间,而是以厘秒为单位:

if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeCentiseconds = 10000;
      AllowResetTimer = NO;
   }
}
timeCentiseconds -= 67;

最后,在输出中除以100:

timerLabel.text=[NSString stringWithFormat:@"Time: %d.%02d", timeCentiseconds/100, timeCentiseconds%100];

或者,使用double

double timeSeconds;
...
if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeSeconds = 100;
      AllowResetTimer = NO;
   }
}
timeSeconds -= 0.67;
timerLabel.text=[NSString stringWithFormat:@"Time: %.2g", timeSeconds];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM