1
\$\begingroup\$

I am working with C and SDL2 and just wanted some insight as to how to properly apply interpolation to the rendering.

EDIT - some clarification, update() input() and render() are just hypothetical stubs, the real code is messy and long as I learn SDL2.

while (!quit) {
    current = SDL_GetTicks();
    elapsed = current - previous;
    previous = current;
    lag += elapsed;

    input();

    while (lag >= ms_per_update)
    {
        update();
        lag -= ms_per_update;
    }

    interpolation = (float)lag / (float)ms_per_update;

    printf("Interploation: %f\r\n", interpolation);

    render(interpolation);
}

This is something that has always kind of baffled me -

lets say that in update() if SPACE pressed we start a jump animation and movement. So sprite.y += 2 to move it.

Where does that movement of one pixel happen? Does it happen in update()?

If the movement happens in update() then how do i properly apply the interpolation in render() since my item has already been moved (during the update)?

  • Lets say i have a bullet at (x=10, y=10)
  • It's velocity is 10 pixels per update.
  • use clicks button to shoot
  • first update bullet is moved to (x=20, y=10)
  • render(interpolation) // lets say it is 0.5) // lots of on screen lag from awesome effects
  • second update bullet is moved to (x=30, y=10)
  • third update bullet is moved to (x=40, y=10)
  • render(interpolation) // lets say it is .09 from lots of lag

How is the interpolation value applied to the bullet so that it appears to pass smoothly across the screen. What information is known during render to apply the interpolation? Would a struct containing the origin point, current velocity (or amount moved since last render), and current location suffice?

\$\endgroup\$
2
\$\begingroup\$

Basically, you have to store the two most recent "snapshots" produced by the update step. These snapshots have all the information needed to render the scene, such as the positions and rotations of all your sprites.

To properly interpolate, the rendering system time lags behind real time by the interval of an update, so if your game updates at 50Hz, the rendering system is behind 20ms. This ensures that the rendering time lies between the snapshots.

To render the scene, you interpolate between the snapshots. Be wary that objects that are orbiting something extremely quickly will be rendered incorrectly if you interpolate between their positions and not their polar coordinates relative to the center of their orbit. You could also integrate acceleration and velocity to more accurately interpolate, but if you're going to go this far you might as well just run your update step more often.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.