I’m going to try to explain a timing loop I’ve used in pretty much all my recent games.
It lets you have discrete time steps for game logics, and still works with high FPS.
There are two kinds of “ticks”, or pulses that are sent through the system: gameticks and clientticks.
Gameticks are sent at a regular interval, and clientticks are sent as often as possible.
First we define how often we want the gameticks, and a very useful derived value
private static final int GAMETICKS_PER_SECOND = 25;
private static final int MILLISECONDS_PER_GAMETICK = 1000 / GAMETICKS_PER_SECOND;
(This can also be done in the constructor if you dislike hardcoded stuff)
Then we build the run method that calls gameTick() and clientTick()
long previousTime = timer.getTimeInMillis();
long passedTime = 0;
while (keepGoing)
{
clientTick();
long time = timer.getTimeInMillis;
passedTime += (time-previousTime);
previousTime = time;
while (passedTime>MILLISECONDS_PER_GAMETICK)
{
gameTick();
passedTime-=MILLISECONDS_PER_GAMETICK;
}
}
The basic idea is to call clientTick() while there is less “unprocessed time” in passedTime than MILLISECONDS_PER_GAMETICK, then call gameTick() until passedTime is lower than MILLISECONDS_PER_GAMETICK again.
This ensures that gameTick() will be called exactly GAMETICKS_PER_SECOND times per seconds on average, and that clientTick() will be called as often as possible.
(more to come)