Sunday, June 26, 2011

Tick Counter for Slow Computers

Normally when making a game/animation loop which should run at a realistic looking speed, I do the following:

while(Playing)
{
    updateGame();
    System.pause(delayTime);
}

which is fine as long as the game code executes in a time much less than the refresh period (i.e. 1/(refresh rate)). However, when the game loop takes a longer time so that the delay you need to give is quite small, then the computer optimized for a slower computer (as I have at home) will run way too fast on a less ancient computer (as I have at work.)

This can be partially overcome (assuming that you computer can at least run the program with zero delay) by implementing a feedback loop which adjusts the delay time to keep a fixed number of cycles per second.

This is actually quite easy to do: say we want x cycles/s and we get y cycles/s -

int t = getCurrentTime();
int tickCounter = 0;
while(Playing)
{
    tickCounter++; 
    time = getCurrentTime()-t; 
    if(time > 1000ms) 
    { 
        delay = updateDelay(tickCounter); 
        t = getCurrentTime(); // reset time 
        tickCounter=0; 
    } 
    updateGame(); 
    System.pause(delay) 
} 
 
public int updateDelay(int y) 
{ 
    return delay*y/x; 
}
... and that's it.

A simple implementation of this can be found here: basically, it is an Applet which runs a stopwatch (it has to do something) and adjusts the delay per loop so that the program executes a specified number of iterations per second. The functionality of the stopwatch is unaffected by the background feedback loop as desired.




... and the source code is here.