游戏循环中的滞后

时间:2019-01-18 18:00:18

标签: java game-loop

这是我的游戏循环代码:

public void run() {
    running = true;

    boolean renderCheck = false;
    double firstTime = 0;
    double lastTime = System.nanoTime() / 1000000000.0;
    double passedTime = 0;
    double unprocessedTime = 0;

    double frameTime = 0;
    int frames = 0;
    int fps = 0;

    while (running) {
        firstTime = System.nanoTime() / 1000000000.0;
        passedTime = firstTime - lastTime;
        lastTime = firstTime;

        unprocessedTime += passedTime;
        frameTime += passedTime;

        while (unprocessedTime >= UPDATE_CAP) {
            tick();
            unprocessedTime -= UPDATE_CAP;
            renderCheck = true;
        }

        if (frameTime >= 1.0) {
            frameTime = 0;
            fps = frames;
            frames = 0;
            System.out.println(fps);
        }

        if (renderCheck) {
            render();
            frames++;
            renderCheck = false;
        } else {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

这是一个渲染区域:

private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        this.createBufferStrategy(3);
        return;
    }

    Graphics graphics = bs.getDrawGraphics();

    graphics.setColor(Color.black);
    graphics.fillRect(0, 0, WIDTH, HEIGHT);

    handler.render(graphics);

    graphics.dispose();
    bs.show();
}

这是一个滴答声部分(不必显示其他代码供处理程序使用,因为阅读起来会如此之多):

private void tick() {
    handler.tick();
}

所以主要的问题是接下来的事情。当我按下按钮时,角色必须开始移动。而且,实际上确实如此,但是有一些延迟,使该过程看起来很糟糕。不到一秒钟,一切都进展顺利。 (我已经检查过CPU负载-一切正常)

仅在Linux PC上会发生此问题。我已经在Windows 10上以exe格式对其进行了检查,并且一切正常!有点奇怪。

2 个答案:

答案 0 :(得分:0)

This lazy initialization might be your problem:

private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        this.createBufferStrategy(3);
        return;
    }
    ...

Did you consider the fact on the first call of your render() function the getBufferStrategy() will return null at which point

  • you will first create it (that is ok)

  • then return without any action (that is suspicious)

Subsequent calls of render would actually perform rendering ... later. If you know for sure that you will need that bufferStrategy anyway, it would make sense to create it straight away when initializing your system.

答案 1 :(得分:0)

S,终于我找到了解决此问题的解决方案!

只需通过编写以下代码在静态main方法中将系统属性设置为java2d即可:

System.gc()