倒计时器iphone sdk?
我的游戏中有一个倒计时器,我正在尝试弄清楚如何制作它,以便它显示两位小数并在我的表格中显示两位小数的记录。现在它作为一个整数倒数并作为一个整数记录。有什么想法吗?
-(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];
I have a countdown timer in my game and I'm trying to figure out how to make it so that it shows two decimal places and records with 2 decimal places in my table. Right now it counts down as a whole number and records as a whole number. Any ideas?
-(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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了实现亚秒级更新,计时器的间隔需要<< 1. 但是 NSTimer 的精度只有 50 ms 左右,所以
scheduledTimerWithTimeInterval:0.01
不起作用。此外,计时器可能会因各种活动而延迟,因此使用 timeSeconds 会导致计时不准确。通常的方法是将 NSDate now 与计时器启动时的日期进行比较。然而,由于此代码是针对游戏的,因此当前的方法可能会给玩家带来更少的挫败感,尤其是。如果程序或后台进程消耗大量资源。
首先要做的是将 countdownTimer 转换为亚秒间隔。
然后,不要以秒为单位倒计时,而是以厘秒为单位倒计时:
最后,在输出中除以 100:
或者,使用
double
:To have sub-second updates, the timer's interval needs to be < 1. But the precision of NSTimer is just around 50 ms, so
scheduledTimerWithTimeInterval:0.01
will not work.Moreover, the timer can be delayed by various activities, so using
timeSeconds
will lead to inaccurate timing. The usual way is compare the NSDate now with the date when the timer starts. However, as this code is for a game, the current approach may cause less frustration to players esp. if the program or background processes consumes lots of resources.The first thing to do is to convert the countdownTimer to sub-second interval.
Then, don't count down the time by seconds, but centiseconds:
Finally, divide by 100 in the output:
Alternatively, use a
double
: