I am trying to create a frame independent game loop.
I am currently using the following code
private class MainGameThread extends Thread {
public static final int PAUSE_SLEEP_TIME = 10;
long previous = getCurrentTimeInMillis();
long totalElapsed = 0;
long gameTimeStart = 0;
long currentTime = getCurrentTimeInMillis();
long accumulatorTime = 0;
@Override
public void run() {
gameTimeStart = getCurrentTimeInMillis();
while (mIsRunning) {
// Pause game
while (mIsPaused) {
try {
Thread.sleep(PAUSE_SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long current = getCurrentTimeInMillis();
long elapsed = current - previous;
previous = current;
processGameInput();
updateGameState(elapsed);
totalElapsed += elapsed;
if (totalElapsed > MainGame.MS_PER_FRAME) {
drawGame();
totalElapsed -= MainGame.MS_PER_FRAME;
if (totalElapsed > MainGame.MS_PER_FRAME) {
Log.e("GAME", "Performance warning, rendering or update took too long");
}
}
checkIfGameShouldStop(gameTimeStart);
}
shutdownGracefully();
}
private void shutdownGracefully() {
}
}
It works, however it performs differently on different devices.
In my game models update method
I am performing the following actions
mCenterX += (mVelocityVector.x * timeElapsed);
mCenterY += (mVelocityVector.y * timeElapsed + gameSpeed.getValue())
I have read this article, but I can't understand the final example:
double t = 0.0;
double dt = 0.01;
double currentTime = hires_time_in_seconds();
double accumulator = 0.0;
State previous;
State current;
while ( !quit )
{
double newTime = time();
double frameTime = newTime - currentTime;
if ( frameTime > 0.25 )
frameTime = 0.25;
currentTime = newTime;
accumulator += frameTime;
while ( accumulator >= dt )
{
previousState = currentState;
integrate( currentState, t, dt );
t += dt;
accumulator -= dt;
}
const double alpha = accumulator / dt;
State state = currentState * alpha +
previousState * ( 1.0 - alpha );
render( state );
}
What does the State class object mean in this case?
Could someone please help to adapt this example to my case or explain the example from the article and how I could update my loop to be frame independent?