在固定的时间步长游戏循环中框架封顶 - Java

时间:2018-01-23 22:02:06

标签: java frame-rate java-2d game-loop

我目前正在开发基于Java 2D的游戏,这是我目前基于教程的游戏循环:

public class FixedTSGameLoop implements Runnable
{
private MapPanel _gamePanel;

public FixedTSGameLoop(MapPanel panel) 
{
    this._gamePanel = panel;
}

@Override
public void run() 
{
    long lastTime = System.nanoTime(), now;
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (this._gamePanel.isRunning())
    {
        now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1)
        {
            tick();
            updates++;
            delta--;
        }
        render();
        frames++;
        if (System.currentTimeMillis() - timer > 1000)
        {
            timer += 1000;
            System.out.println("FPS: " + frames + " TICKS: " + updates);
            frames = 0;
            updates = 0;
        }
    }
}

private void tick()
{
    /**
     * Logic goes here:
     */
    this._gamePanel.setLogic();
}

private void render()
{
    /**
     * Rendering the map panel
     */
    this._gamePanel.repaint();
}
}

现在,我想为帧率设置一定的上限。我该如何以最有效的方式做到这一点? *关于游戏循环本身的任何其他一般提示将非常感谢! 谢谢!

1 个答案:

答案 0 :(得分:0)

这就是我设置游戏循环的方法。您可以将frameCap更改为您想要的任何金额。

    int frameCap = 120;
    int fps = 0;

    double delta = 0D;
    long last = System.nanoTime();
    long timer = 0L;

    while (true) {
        long now = System.nanoTime();
        long since = now - last;

        delta += since / (1000000000D / frameCap);
        timer += since;
        last = now;

        if (delta >= 1D) {
            tick();
            render();

            fps++;

            delta = 0D;
        }

        if (timer >= 1000000000L) {
            System.out.println("fps: " + fps);

            fps = 0;

            timer = 0L;
        }
    }