Reputation: 11
As practice I tried to make a simple program where all you do is control the square around the screen. I`ve tried to make a game loop with interpolation however I am having issues with it, It often stutters and I dont know why. Ive tried removing Thread.sleep(1); to see if this is the issue. if I remove this it actually will decrease the stutter and the fps will jump from around 300 fps to around 8000 fps. But of course if I made this game more complex, I wouldnt be able to get 8000 fps so I wanted to see if the stuttering is still here if I only have around 300 fps so what I did is add a bunch of squares to the screen. This dropped the fps to around 300 and what I noticed is that the stuttering was back. Ive looked at Game loop and Fix your timestep but I couldnt find a solution. What am I doing wrong?
Game loop:
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();
}
}
render method:
private void render(double delta) {
BufferStrategy bs = window.getBufferStrategy();
Graphics g = bs.getDrawGraphics();
g.setColor(Color.DARK_GRAY);
g.fillRect(0,0,Window.WIDTH, Window.HEIGHT);
player.render(g, delta);
bs.show();
g.dispose();
}
Player`s render method:
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);
}
Upvotes: 1
Views: 326
Reputation:
You need to use delta like:
state = currentState * delta + previousState * ( 1.0 - delta );
When accumulator equals timePerUpdate (60 FPS) delta will be 0.
Since your code never uses (1.0 - delta),
double renderX = oldX + (x - oldX) * delta;
double renderY = oldY + (y - oldY) * delta;
means you're ignoring the update, and thus stutter.
Upvotes: 2