I am writting a simple game, and I want to cap my framerate at 60 fps without making the loop eat my cpu. How would I do this?
Here's how I did it in C++... I'm sure you can adapt it.
void capFrameRate(double fps) {
static double start = 0, diff, wait;
wait = 1 / fps;
diff = glfwGetTime() - start;
if (diff < wait) {
glfwSleep(wait - diff);
}
start = glfwGetTime();
}
Just call it with capFrameRate(60)
once per loop. It will sleep, so it doesn't waste precious cycles. glfwGetTime()
returns the time since the program started in seconds... I'm sure you can find an equivalent in Java somewhere.