Here’s my current game loop code I’m using in my WIP project.
while (running) {
shouldRender = false;
long now = System.nanoTime();
unprocessed += (now - lastTime) / nsPerTick;
lastTime = now;
while (unprocessed >= 1) {
tick++;
unprocessed -= 1;
}
//Limits the number of ticks per unprocessed frame.
int toTick = tick;
if (tick > 0 && tick < 3)
toTick = 1;
if (tick > 7)
toTick = 7;
for (int i = 0; i < toTick; i++) {
tick--;
tick();
shouldRender = true;
}
if (shouldRender) {
frames++;
render();
}
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
}
if (System.currentTimeMillis() - lastTimer > 1000) {
lastTimer += 1000;
fps = frames;
System.out.println("FPS: " + Integer.toString(fps));
frames = 0;
}
}
The flaw for this game loop is when the user is not focused on the Java application, the unprocessed ticks will incrementally go up until it gets refocused. When this happens, tick counts will briefly speed up about %300 or so until it throttles back down to normal.
How do I fix this flaw?