将计时器循环设置为固定时间



我正在创建一个游戏。当用户完成游戏时,我正在向他展示分数。为了使它具有交互性,我将分数从 0 计算到分数。

现在,由于用户可以赚取 10 点或 100,000 点,我不希望 hime 等待太久,所以我希望无论分数是多少,总时间都会固定下来。

所以我这样做了,但似乎计时器间隔不受间隔值的影响。

问题出在哪里?

///score timer
-(void)startScoreCountTimer:(NSNumber*)score{
finishedGameFinalScore = [score integerValue];
CGFloat finishedGameFinalScoreAsFloat = [score floatValue];
CGFloat interval = 2.0f/finishedGameFinalScoreAsFloat;
NSLog(@"interval = %f",interval);
NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
timer = [[NSTimer alloc] initWithFireDate:fireDate
                                 interval:interval
                                   target:self
                                 selector:@selector(timerMethod:)
                                 userInfo:nil
                                  repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
}
- (void)timerMethod:(NSTimer*)theTimer{
scoreCount++;
finalScoreLabel.text = [NSString stringWithFormat:@"%i",scoreCount];
   if (scoreCount == finishedGameFinalScore ||finishedGameFinalScore ==0) {
    [theTimer invalidate];
    scoreCount=0;
    [self updateMedalsBoard];
   }
}

我会使用重复的NSTimer而不是runloop。

aTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerMethod:) userInfo:nil repeats:NO]; 

并将timerMethod更改为更类似于以下内容的内容:

- (void)timerMethod:(NSTimer*)theTimer{  
     scoreCount = scoreCount + (finishedGameFinalScore * (numberOfSecondsYouWantToRun/100));
     finalScoreLabel.text = [NSString stringWithFormat:@"%i",scoreCount];
     if (scoreCount == finishedGameFinalScore ||finishedGameFinalScore ==0) {
         [theTimer invalidate];
         scoreCount=0;
         [self updateMedalsBoard];
     } else {
         theTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerMethod:) userInfo:nil repeats:NO];
     }
} 

这将使 scoreCount 根据其总分按非固定数字递增。因此,如果您希望分数计数器运行 2 秒并且您的玩家得分为 100,那么它将每十分之一秒扣 2 分。如果你的玩家得分为 100,000 分,则分数将每十分之一秒增加 2000 分。

NSTimers 不能保证每 X 秒(或毫秒,或者在您的情况下为微秒)触发一次。 您只能确定它们会在 X 秒(等)过后的某个时间触发。 在您的情况下,看起来您一次只增加一个点,这在 NSTimer 有机会再次触发之前占用了主线程上的时间,这会减慢整个过程。

更好的方法可能是简单地让计时器每 0.1 秒重复一次,持续 2 秒。 在每次调用 timerMethod: 时,将总分的 1/20 相加,直到在上次迭代中达到最终总分。 当然,你可以玩弄确切的间隔来找到看起来不错的东西。

最新更新