当前尝试将游戏循环管理到稳定的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());
}
非常感谢您的帮助!