I am just a newbie game developer, I am trying to create a frame independent game loop.
I don't need to process complex physics equitations, integrate forces or anything else. My game doesn't have physics at all except of speed and acceleration.
The game is really simple. Different types of shapes are falling down and you need to skip or to catch it, no bouncing and something else.
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);
}
}
}
But it doesn't work well on different devices, on some devices it runs faster, on some slower.
The only thing that is changed in my
update method.
mCenterX += (mVelocityVector.x * timeElapsed);
mCenterY += (mVelocityVector.y * timeElapsed + gameSpeed.getValue())
I need it to be frame independent.
I have found an interesting article about the game loop, but didn't get an idea.
https://gafferongames.com/post/fix_your_timestep/Here is the final code
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 );
}
I guess I don't need methods like
integrate in my case, because there is nothing to integrate.
But still not sure what should I put in the
State class ?
Could someone explain the best choice in my case, for my simple game. I need just to follow best practices and make it frame independent.
I would be grateful fro any help.
Thanks