Java Game Loop每秒更新帮助 - 每秒帧数

时间:2015-12-10 21:53:17

标签: java game-loop

假设我使用这个游戏循环并希望保持60 FPS,那么适当的UPS(每秒更新)是多少?它也应该是60吗?谢谢你的帮助

  @Override
public void run() {

long initialTime = System.nanoTime();
final double timeU = 1000000000 / UPS;
final double timeF = 1000000000 / FPS;
double deltaU = 0, deltaF = 0;
int frames = 0, ticks = 0;
long timer = System.currentTimeMillis();

    while (running) {

        long currentTime = System.nanoTime();
        deltaU += (currentTime - initialTime) / timeU;
        deltaF += (currentTime - initialTime) / timeF;
        initialTime = currentTime;

        if (deltaU >= 1) {
            getInput();
            update();
            ticks++;
            deltaU--;
        }

        if (deltaF >= 1) {
            render();
            frames++;
            deltaF--;
        }

        if (System.currentTimeMillis() - timer > 1000) {
            if (RENDER_TIME) {
                System.out.println(String.format("UPS: %s, FPS: %s", ticks, frames));
            }
            frames = 0;
            ticks = 0;
            timer += 1000;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

应该修复更新

double previous = getCurrentTime();
double lag = 0.0;


    while (true) {

        double current = getCurrentTime();
        double elapsed = current - previous;
        previous = current;
        lag += elapsed;

        processInput();

        while (lag >= MS_PER_UPDATE) {
            update();
            lag -= MS_PER_UPDATE;
        }

        render();
}

如果实时和游戏时间之间的差异高于两次更新之间的所需时间,则必须更新。 如果滞后较低,则意味着您无需更新,但无论如何都可以渲染。

此处有更好的解释:http://gameprogrammingpatterns.com/game-loop.html