I am using this code structure below from here http://www.koonsolo.com/news/dewitters-gameloop/ to set a game loop that processes based on a set fps but renders/draws at the most possible. How would one implement a cap on the drawing fps so as not to use up all the processing power /battery life. or to limit it for v-syncing.
const int TICKS_PER_SECOND = 60;
const int SKIP_TICKS = 1000000000 / TICKS_PER_SECOND;
const int MAX_FRAMESKIP = 5;
DWORD next_game_tick = GetTickCount();
int loops;
float interpolation;
bool game_is_running = true;
while( game_is_running ) {
loops = 0;
while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
update_game();
next_game_tick += SKIP_TICKS;
loops++;
}
interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
/ float( SKIP_TICKS );
display_game( interpolation );
}
I assume that you are actually doing proper motion interpolation? Otherwise it doesn't make sense to render faster than your game update: you'll just be rendering all the objects again in exactly the same position.
I'd suggest the following:
Thread.sleep(millis)
call in to stop the busy-looping. Probably a Thread.sleep(5)
is fine, since you are just going to do a quick check for whether you are ready for the next update.display_game
call to see if at least a certain number of millisconds has elapsed since the last display_game. For example, if you make this 10ms then your frame rate will be limited to 100 FPs. There are also a couple of other things that are a bit unclear in your code:
long time=System.nanoTime()
or similar.....Finally, you should also consider whether you want to decouple your update loop from the rendering code and have them running on different threads. This is trickier to get right since you may need to lock or take snapshots of certain objects to ensure they don't change while you are rendering them, but it will help your performance and scalability on multi-core machines (which is most of them nowadays!)