Search code examples
c++game-physicssfmltimedeltalinear-interpolation

Is my solution to fixed timestep with delta time and interpolation wrong?


I am trying to write simple loop with fixed delta time used for physics and interpolation before rendering the state. I am using Gaffer on games tutorial on fixed timesteps and I tried to understand it and make it work.

float timeStep = 0.01;
float alpha = 1.0;
while (isOpen()) {
    processInput();
    deltaTime = clock.restart(); // get elapsed time
    if (deltaTime > 0.25) { deltaTime = 0.25; } // drop frame guard
    accumulator += deltaTime;
    while (accumulator >= timeStep) {
        // spritePosBefore = sprite.getPosition();
        accumulator -= timeStep;
        // sprite.move(velocity * timeStep, 0);
        // spritePosAfter = sprite.getPosition();
    }
    if (accumulator > timeStep) { alpha = accumulator / timeStep; } else { alpha = 1.0; }
    // sprite.setPosition(Vector2f(spritePosBefore * (1 - alpha) + spritePosAfter * alpha));
    clear();
    draw(sprite);
    display();
}

Now, everything looks good. I have fixed timestep for physics, draw whenever I can after physics are updated and interpolate between two positions. It should work flawless but I can still see sprite stuttering or even going back by one pixel once in a while. Why does it happen? Is there any problem with my code? I spent last two days trying to understand game loop which would ensure me flawless motions but it seems like it doesn't work as I thought it will. Any idea what could be improved?


Solution

  • You should remove the if statement and always calculate alpha; the if statement will never be executed as the condition is always false after the while loop is exited!

    After the loop the accumulator will be between 0 and timeStep so you just end up drawing the latest position instead of interpolating.