I’ve been having a bit of trouble coming up with a decent game loop (or maybe this is decent, I just feel it could be better). Taken directly from the game I’m working on, my loop is below:
public void loop() {
Date startTime = new Date();
Date previousRepaint = startTime;
Date currentTime = startTime;
float delta;
float redrawsPerSecond = 1000/maxFps;
// While the game is not over...
while(!gameOver) {
currentTime = new Date();
delta = currentTime.getTime()-previousRepaint.getTime();
update(delta);
repaint();
previousRepaint = currentTime;
// Limit repaint to the max FPS.
if(delta <= redrawsPerSecond) {
try { Thread.sleep(10); } catch(Exception e) { /* pass */ }
}
}
}
I see this as a sort of passive limitation (using Thread.sleep() instead of limiting the redraws conditionally beforehand). One thing to note is when I leverage the delta properly, I can keep CPU usage down to between 15-20% with very smooth animation.
I’m really looking for any sort of advice on this. Is there generally a better way to go about the game loop? Is this code fine, but maybe a few tweaks here and there?