zsdl/README.md
2025-01-07 16:34:47 -07:00

1.3 KiB

Physics and Timing

I want to have decoupled rendering with the ability to render partial physics simulations, so it needs to be deterministic.

Based on this snippet from this article

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 );
}

or from this medium article

while(running){
    computeDeltaTimeSomehow();
    accumulator += deltaTime;
    while(accumulator >= 1.0/60.0){
        previous_state = current_state;
        current_state = update();
        accumulator -= 1.0/60.0;
    }
    render_interpolated_somehow(previous_state, current_state, accumulator/(1.0/60.0));
    display();
}