59 lines
1.3 KiB
Markdown
59 lines
1.3 KiB
Markdown
## 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](https://gafferongames.com/post/fix_your_timestep/)
|
|
|
|
```c
|
|
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](https://medium.com/@tglaiel/how-to-make-your-game-run-at-60fps-24c61210fe75)
|
|
|
|
```c
|
|
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();
|
|
}
|
|
```
|