作为练习,我尝试制作一个简单的程序,您只需控制屏幕周围的方块即可。我尝试使用插值制作游戏循环,但是我遇到了问题,它经常口吃,我不知道为什么。我试过删除 Thread.sleep(1);看看是不是这个问题。如果我删除它,它实际上会减少口吃,并且 fps 将从大约 300 fps 跳到大约 8000 fps。但当然,如果我让这个游戏更复杂,我将无法获得 8000 fps,所以我想看看如果我只有 300 fps 左右,口吃是否仍然存在,所以我所做的是在屏幕上添加一堆方块.这将 fps 降至 300 左右,我注意到口吃又回来了。我查看了 Game loop 和 Fix your timestep,但找不到解决方案。我做错了什么?
游戏循环:
int targetUps = 60;
int timePerupdate = 1_000_000_000 / targetUps;
long oldTime = System.nanoTime();
long newTime;
int accumulator = 0;
int upsTimer = 0;
int upsCounter = 0;
int fpsCounter = 0;
while(true) {
newTime = System.nanoTime();
accumulator += newTime - oldTime;
upsTimer += newTime - oldTime;
oldTime = newTime;
while(accumulator >= timePerupdate) {
update();
accumulator -= timePerupdate;
upsCounter++;
}
render(Math.min(1.0f,(double) accumulator / timePerupdate));
fpsCounter++;
if(upsTimer >= 1_000_000_000) {
System.out.println("UPS: " + upsCounter + " | " + "FPS: " + fpsCounter);
fpsCounter = 0;
upsCounter = 0;
upsTimer = 0;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
渲染方法:
private void render(double delta) {
BufferStrategy bs = window.getBufferStrategy();
Graphics g = bs.getDrawGraphics();
g.setColor(Color.DARK_GRAY);
g.fillRect(0,Window.WIDTH,Window.HEIGHT);
player.render(g,delta);
bs.show();
g.dispose();
}
播放器的渲染方法:
public void render(Graphics g,double delta) {
g.setColor(Color.GREEN);
double renderX = oldX + (x - oldX) * delta;
double renderY = oldY + (y - oldY) * delta;
g.fillRect((int) renderX,(int) renderY,32,32);
}