I've been working on development for an Android game, and this is the game loop I have so far:
private static final int MAX_UPDATES_PER_DRAW = 10;
private long timeAccumulator = 0;
private long lastTime = System.nanoTime();
@Override
public void onDrawFrame(GL10 unused)
{
// Use this structure to set constant dt on a given frame
// Limit updates to avoid spiral of death;
long time = System.nanoTime();
timeAccumulator += time - lastTime;
lastTime = time;
int updateCount = 0;
while (timeAccumulator >= dt && updateCount < MAX_UPDATES_PER_DRAW)
{
// Update
game.update((double) dt / (double) NANOS_PER_SECOND); // Divide by 1 000 000 000 for seconds
timeAccumulator -= dt;
updateCount++;
// Account for any time lost
time = System.nanoTime();
timeAccumulator += time - lastTime;
lastTime = time;
}
// Calculate alpha to interpolate between states for smooth animation
// to avoid temporal aliasing. Alpha ranges from 0.0 - 1.0
double alpha = Maths.clamp((double) timeAccumulator / (double) dt, 0.0, 1.0);
// Draw game.
game.draw(alpha);
// Check for OpenGL errors.
int error = GLES20.glGetError();
if (error != 0)
throw new RuntimeException("OpenGL Error: " + error);
// Account for any time lost
time = System.nanoTime();
timeAccumulator += time - lastTime;
lastTime = time;
// Delay to maintain fps for battery conservation
long timeUntilUpdate = dt - timeAccumulator;
if (timeUntilUpdate > 0)
{
try
{
Thread.sleep(timeUntilUpdate / NANOS_PER_MILI);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
I'm trying to find a near perfect solution for a fixed time step, but noticing slight stutter (may be due to external reasons like garbage collection) with this one. I plan to break my update(dt) into update(dt) and stepPhysics(dt) and only do a fixed timestep and physics related calculations in stepPhysics to save performance.
Are there any glaring flaws with this that anybody could point out?