(增量时间)在Java中获得60秒更新 [英] (Delta time) Getting 60 updates a second in java

查看:249
本文介绍了(增量时间)在Java中获得60秒更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过几次这个代码.

I've seen this code several times.

long lastTime = System.nanoTime();
final double ticks = 60D;
double ns = 1000000000 / ticks;    
double delta = 0;

上面的代码花费系统时间并将其存储到lastTime. 60个滴答应等于每秒更新的次数.

The code above takes the System time and stores it to lastTime. The 60 ticks should equate to the number of times to update per second.

while(running){
    long now = System.nanoTime();
    delta += (now - lastTime) / ns;
    lastTime = now;
    if(delta >= 1){
        tick();
        delta--;
    }

now并减去lastTime,然后将其转换为纳秒/60.是否可以保证nowlastTime到nano的时间差超过60,将导致增量大于或等于1,每秒60次?我不明白为什么tick();每秒将运行约60次.根据我的计算,每次循环运行的增量都会增加0.0025左右.

It takes now and subtracts lastTime, then converts it to nanoseconds/60. Is there some guarantee that the difference in time between now and lastTime to nano over 60 will cause delta to be greater than or equal to 1, 60 times per second? I can't understand why tick(); will run around 60 times per second. From my calculation every time the loop runs delta increases by 0.0025 or so.

推荐答案

我不知道tick()中有什么,但我不确定,但是我猜想它也使用60D尝试睡眠约正确的时间长度?因此:不,没有保证,这是此代码可修复的地方.

Without knowing what's in tick(), I can't be sure, but I'd guess that it also uses 60D to attempt to sleep for about the correct amount of time? So: no, there's isn't a guarantee, which is what this code is there to fix.

这是在说:如果tick()睡了不到一刻,那么就什么也不要做;如果睡着一刻或更多,请勾选一次."

It's saying "If tick() slept for less than a tick, then don't do anything; if it slept by a tick or more, tick once".

大概,如果滴答声结束的时间足够长(例如80ns然后80ns,这意味着第一个循环将滴答声增加,第二个循环将滴答声增加2),那么最终将出现另一个仅具有40ns增量的循环,从而导致所有均匀.

Presumably, if ticking goes over enough (for example 80ns then 80ns, meaning that the 1st loop increments tick and the second increases it by 2), then eventually there will be another loop that only has a 40ns delta, causing everything to even out.

这篇关于(增量时间)在Java中获得60秒更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆