首页 > 解决方案 > 循环计数不是预期的

问题描述

目前正在尝试将游戏循环管理到稳定的 60 帧。我按照我看到的例子到了一个 T,但没有得到预期的输出。开始怀疑我的电脑是不是很慢。

我使用以下代码来管理每个循环的渲染次数:

@Override
public void run() {

    int fps = 60;   //Number of renders wanted per second
    double timePerTick = 1000000000/fps;    //Alotted nanoseconds given desired fps
    double delta = 0;
    long now;
    long lastTime = System.nanoTime(); 
    int ticks = 0; //To track the number of times render() is called in 1 second

    while(isRunning) {

        now = System.nanoTime();
        delta += (now - lastTime)/timePerTick; //Delta here is very small #. Represents amount of the timePerTick used after looping through one time.
        timer += now - lastTime;
        lastTime = now;


        if(delta >= 1) {//This dictates whether a render occurs or not.
            render();
            ticks++;
            delta = 0;
        }

        if(timer >= 1000000000) {//Prints out how many renders occurred in one second
            System.out.println("FR at " + ticks);
            ticks = 0;
            timer = 0;

        }

    }
}

在我遵循的示例中,此代码每次打印输出一致地生成 60 帧。我的始终打印出 23、24、17、20 等。无论我如何将其更改为if(delta >= 1)if(delta >= .0000001)它仍然每秒打印出大约相同数量的渲染/帧。

显然,使用较低的阈值,应该会发生更多的渲染......但这并没有发生。所以在这一点上,我非常困惑。我知道我可以使用Thread.sleep()它,但不能保证它是准确的。

我不确定你们是否想看到我的 render() 方法,但这里是:

private void render() {
    strategy = myCanvas.getBufferStrategy();

    if(strategy == null) {
        myCanvas.createBufferStrategy(3);
        return;
    }


    do {
        do {

            g = strategy.getDrawGraphics();
            g.clearRect(0, 0, 1000, 1000);

            BufferedImage myImage = ImageLoader.getImage(path);//Do this in an instantiation method


            g.drawImage(myImage.getSubimage(0, 0, 110, 125), x, 0, 300, 300, null);

            strategy.show();
            x++;

        }while(strategy.contentsRestored());

        g.dispose();

    }while(strategy.contentsLost());

}

任何帮助是极大的赞赏!

标签: javaloopsgraphics

解决方案


推荐阅读