Limiting FPS in Java - is this code working correctly?
I have a game loop (frame-independent as outlined here.)
Now, this works great, the objects in my game move to the same positions at the same time regardless if it's at 10 FPS or 1000 FPS.
The problem is, the frame rate can get astronomically high, which is a bad thing because it causes unnecessary stress to the graphics card and generates a lot of heat. So I want to limit it. This is my code so far:
final long targetFPS = 60;
long lastUpdate = System.currentTimeMillis();
public void run() {
while (true) {
// unimportant, some logic is snipped off here
this.update();
this.render();
this.draw();
// important:
try {
Thread.sleep( Math.max( (1000/targetFPS) - (System.currentTimeMillis() - lastUpdate), 0) );
} catch (InterruptedException ie) {}
lastUpdate = System.currentTimeMillis();
}
}
The logic being, it will try to aim for 1000/FPS milliseconds (so for 60 FPS, it will sleep for 17ms), then it will subtract the time needed to sleep for the next frame based on how long it took for the current frame to update. If it took longer than the 17ms to update, then it will sleep for 0 seconds and move onto the next frame.
This is mostly a code review question because I've never made my own game loop; I would use engines that handled this kind of thing for me.
It seems to work well, but I don't know if my logic is sound.
Posted Mar 24, 2012, 10:04 PM UTC