Sunday, August 12, 2007

Fixed time step

i have added fixed time step with new interagor (midpoint or rk4) to the physics simulation (objects movement), until now i used the frame dt with euler (yes euler - very lame) integration and the results was very bad, the movement was very jerky (very noticeable when fps goes down and up during the game).
the problem is this, when we are using numerical integrations the result depends on the dt, the larger the dt the less accurate result we get, so if develop our simulation to run at 60 fps (dt = 1/60) and at some point the frame rate drops to 10 fps then the result we get is very inaccurate and results very odd movement (or even exploding), this is true for advance integrations as well - verlet, midpoint, rk4 etc...
with the new fixed dt, i assure the physics simulation runs at the same speed as the display frame rate (sync with it), so if the display frame rate is 30 fps and the physics design to run in 60 fps then we need to do 2 physics steps for every display update to make physics in sync.
i also added a final touch that interpolate between 2 physics states (previous and current) based on some alpha.
interpolation is needed to handle cases when the physics frame rate is not divided by display frame rate (without a remainder), for example the frame rate is 50 fps and the physics is 60 fps, so every frame the algorithm will have to alternate between 2 physics steps or one, this will be good enough to keep it in sync but visually it looks jerky.