3

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

-(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];
4

1 回答 1

2

要进行亚秒级更新,计时器的间隔需要 < 1。但 NSTimer 的精度仅为 50 毫秒左右,因此scheduledTimerWithTimeInterval:0.01无法正常工作。

而且,定时器可以被各种活动延迟,所以使用timeSeconds会导致计时不准确。通常的方法是将 NSDate now 与计时器开始的日期进行比较。但是,由于此代码是针对游戏的,因此当前的方法可能会给玩家带来更少的挫败感,尤其是。如果程序或后台进程消耗大量资源。


首先要做的是将 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];
于 2010-02-13T06:17:59.980 回答