Fix Your Timestep!

September 2, 2006

Introduction

Hello, I’m Glenn Fiedler and welcome to the second article in my series on Game Physics.

In the previous article we discussed how to integrate the equations of motion using an RK4 integrator.

Now that we have a working physics simulation the next thing we want to do is to display it animating on the screen.

The basic idea is this: each frame we advance the simulation forward by some small amount of time then draw it to the screen. By repeating this over and over the objects animate following the laws of physics.

This sounds so simple, but there are many different ways to do it – so read on!

Fixed delta time

One way to step forward is with a fixed delta time value, like 1/60th of a second:

    double t = 0.0;
    double dt = 1.0 / 60.0;

    while ( !quit )
    {
         integrate( state, t, dt );
         render( state );
         t += dt;
    }

This code is absolutely perfect – provided that VSYNC is on, the display refresh rate is 60HZ and your simulation and rendering code always takes less than 1/60th of a second per-frame.

Problem is if your code is unable to make frame, or if the display rate is different – your game runs faster or slower than the speed you intended.

Variable delta time

This this easy to fix. Just measure how much time spent each frame using a high resolution timer, then feed this value back in as the delta time to use next frame:

    double t = 0.0;

    double currentTime = hires_time_in_seconds();

    while ( !quit )
    {
         double newTime = hires_time_in_seconds();
         double dt = newTime - currentTime;
         currentTime = newTime;

         integrate( state, t, dt );
         t += dt;

         render( state );
    }

And this does work. No matter how fast or slow your game is rendering the simulation keeps up and runs at the correct speed. But there is a huge problem with this which I will now explain!

Fix your timestep or explode

Consider this situation: you are working on a physics-based game. You code and tune the simulation on a fast computer. You are easily able to run at 60fps in your test level and everything looks great: your simulation is stable, your collision detection works perfectly and you have the max speed of the objects tuned just right so that they cannot tunnel through walls.

Then you put your game into QA and in less than 10 minutes you get back the following bug report: At low frame rates collision detection stops working, objects are bouncing all over the place and your vehicle suspension code causes the car to bounce halfway across the map and sometimes fall through the terrain.

What the hell is going on?

The problem is that the behavior of your simulation depends on the size of the timestep you take.

There are two main reasons for this. First, numerical integration is only an approximation. Even advanced integrators like RK4 have some error per-frame and each frame you take this slightly incorrect result from the previous frame and feed it back in to the integrator to predict the next step in the simulation and so on. Now, consider what happens when you pass in larger delta time values? It’s less accurate and eventually at some point, depending on the simulation and the integrator you are using, you may actually be able make the simulation explode. Anybody who’s modeled spring physics knows exactly what I’m talking about here.

Second, collision detection is usually discrete in that it relies on the objects actually penetrating at the beginning of the frame to detect collision. But what if your object moves so quickly that it passes entirely through a wall and out the other side in a single frame? Lets say you tuned your collision detection at 100fps then QA tested your game at 10fps – now each object moves 10 times the distance per-frame at the same speed, and if you’re unlucky this might just be far enough to pass completely through something they’d normally collide with.

It should be pretty clear by now that variable delta time can be problematic. So what is the alternative?

Free the physics

What we want is the best of both worlds. A fixed delta time value for the simulation plus the ability to render at different framerates. These two things seem completely at odds, and they are – unless we can find a way to decouple the simulation and rendering framerates.

Here’s what to do. Advance the physics simulation ahead in fixed dt time steps while also making sure that it keeps up with the timer values coming from the renderer so that the simulation appears to run at the correct speed. For example, if the display framerate is 50fps and the simulation runs at 100fps then we need to take two physics steps every display update.

What if the display framerate is 200fps? Well in this case it would seem that we need to take half a physics step each display update, or alternatively, one physics step every two display updates. Even trickier, what if the display framerate is 60fps, but we want our simulation to run at 100fps? There is no easy multiple here. What if VSYNC is disabled and the display frame rate fluctuates from frame to frame?

The trick is to use a time accumulator. Each render update you add the frame time into an accumulator then while there are whole increments of dt remaining you subtract dt and run a physics step.

Effectively the renderer produces time and the physics update consumes it in discrete dt sized chunks.

    double t = 0.0;
    const double dt = 0.01;

    double currentTime = hires_time_in_seconds();
    double accumulator = 0.0;

    while ( !quit )
    {
         double newTime = hires_time_in_seconds();
         double frameTime = newTime - currentTime;
         currentTime = newTime;

         accumulator += frameTime;

         while ( accumulator >= dt )
         {
              integrate( state, t, dt );
              t += dt;
              accumulator -= dt;
         }

         render(state);
    }

If you read the code above carefully you’ll notice that there can be small amounts of frame time left over in the accumulator from one render frame to the next. What is this and what should we do about it?

The final touch

Consider a situation where the display framerate is 60fps and the physics is running at 50fps. There is no easy multiple so the time accumulator causes the simulation to alternate between taking one and two physics steps each frame. This irregular amount of physics steps taken each update causes a subtle but visually unpleasant stuttering of the physics simulation on the screen known as temporal aliasing.

The solution to this is to interpolate between the previous and current physics state based on how much time is left in the accumulator:

    double t = 0.0;
    const 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 += deltaTime;

         while ( accumulator >= dt )
         {
              previousState = currentState;
              integrate( currentState, t, dt );
              t += dt;
              accumulator -= dt;
         }

         const float alpha = accumulator / dt;

         State state = currentState*alpha + previousState * ( 1.0f - alpha );

         render( state );
    }

This looks pretty complicated but here is a simple way to think about it. Any remainder in the accumulator is effectively a measure of just how much more time is required before another whole physics step can be taken. For example, a remainder of dt/2 means that we are currently halfway between the current physics step and the next one. A remainder of dt*0.1 means that the update is 1/10th of the way between the current and the next state.

We can use this remainder value to get a blending factor between the current physics state and the previous state simply by dividing by dt. This gives an alpha value in the range [0,1] which is used to perform a linear interpolation between the two physics states to get the current state to render. This interpolation is easy to do for single values and for vector state values. You can even use it with full 3D rigid body dynamics if you store your orientation as a quaternion and use a spherical linear interpolation (slerp) to blend between the previous and current orientations.

Click here to download the source code for this article.

Further reading

Integration Basics

Integration is used to determine the motion of an object over time. In this article I show how to correctly integrate the equations of motion using an RK4 integrator instead of starting off on the wrong foot with a stupid Euler integrator.

Physics in 3D

Leap ahead from integrating single values to integrating the entire physics state for a cube in three dimensions. Introduces rotational physics concepts including orientation in 3D, angular velocity and momentum, inertia and torque.

Spring Physics

Explains the physics of springs and how to apply them to control physics simulations. Learn how to implement joints, constraints, motors and basic collision response.

Networked Physics

How do network games synchronize physics over the network? This article explains the core techniques used in today’s first person shooters and shows how you can apply these techniques to network your own physics simulations.

{ 90 comments… read them below or add one }

Andrew Ladenberger September 14, 2006 at 12:00 pm

Great article! Best article I’ve read on this important subject. Very nice and clean implementation too.

Do not worry about your difficulties in Mathematics. I can assure you mine are still greater
-Albert Einstein

Reply

Phillip September 15, 2006 at 11:05 am

Excellent articles on game physics. I’m starting to do some research on network-based state machines/physics and they were quite helpful.

Reply

JC September 29, 2006 at 8:17 pm

Thanks so much for posting this! After trying to figure this out after many hours, I was able to quickly come up to speed thanks to this article. Excellent work!

Reply

pTymN October 13, 2006 at 9:44 am

Also, fixed internal framerates help when you do networked games.

Reply

Ruud van Gaal November 21, 2006 at 10:06 am

Given the last interpolation trick with ‘alpha’ blending between states, you’d think that for physics-intensive programs it may be important to really catch up with realtime. I.e. after the while(accumulator>=dt) loop finishes, do a new deltaTime calculation with a new time() call and re-enter the while loop if deltaTime is bigger than some threshold.
I’ve noticed with my car simulator that the physics can take up quite a bit of CPU time, making the last alpha blending call a bit useless if you’re already straying away from the actual time.

Reply

Paul November 28, 2006 at 10:04 am

Excellent article and very helpful to my current situation. Thanks for taking the time to explain this in terms that non-mathematician games programmers can have a half chance of understanding.

Reply

Manu December 29, 2006 at 7:36 pm

Thank you very much!
This solves all my problems :D (really!)

Reply

Matt January 16, 2007 at 3:01 am

I thought I could get by without fixed timestep, however some testers were having issues with the game I’m working on – which were fixed by a fixed timestep. Thanks for writing the article, it saved me tons of time messing around.

Reply

Romz February 9, 2007 at 5:15 pm

Hello, great article! I’v implemented your technique but I’d like your advice about (mega)oversampling.

My project doesn’t do much things so the framerate is insanely high with my PC (3000fps), and the timer of my engine (Ogre) gives me a deltaTime of 0, because it’s has a precision of 1 milisecond, so 1/3000 = 0.00033s = 0.33ms (that’s why I got 0).

I already had this problem with the SDL timer and I guess a QueryPerformanceCounter or any other high precision timer have the same limitation. So I thought putting some ugly Sleep() in the code to obtain a valid deltaTime. How do you think it’s possible to do something about this ?

And even I if want to fix the display framerate, the problem is the same (adding 0 to any accumulator, so it’s never time to update).

Thank you !

Reply

Glenn Fiedler February 10, 2007 at 12:13 pm

use a higher resolution timer, 1ms resolution is next to useless, and is the root cause of your problem

use QueryPerformanceCounter directly!

Reply

Romz February 11, 2007 at 5:53 pm

Everything is now working perfectly, and the interpolation part makes a noticable difference ! Thanks a lot :)

Reply

Leigh McRae February 21, 2007 at 8:33 pm

Very nice article. I was using this method for a game and it actually caused a very subtle bug. When playing very large in game cut scenes, the audio would become out of sync with the animations. I tracked the problem down to delta time accumulating error. The solution instead was to keep a simulation time and a real time. Then the loop is something like:

while ( (time() – simTime)>=dt )
{
simTime += dt
}

You still get error but it’s less. It also works with a crappy timer :)

Leigh

Reply

admin August 1, 2010 at 8:59 am

This is a suitable implementation if you don’t need a fixed delta time, but for general 100% repeatability and same results each time run, I generally prefer the full fixed dt myself. cheers

Reply

Jose Gregoris June 20, 2007 at 7:51 am

Hi Glenn

Thank you for their attention.
I have a question more.
Suppose you, that I update the physics with a dt=0.016 that is the minimum that NewtonGD requires.
The range is of (1/60.. 1/1000) for NewtonGD.
I would update the physics X times before the render, you suppose 16 times.
With a smaller dt=0.01 I would be update the physics more times, you suppose 25 times.

My question is:

Should I have a buffer the position/orientation coming out of newton’s callbacks of variable size?
For example: 16 for dt=0.016 or 25 for dt=0.01.
Is this correct?.
if it is this way.
How I do make to manage after the update of the physics the render?

I implement the solution with 2 variables (currentMatrix previousMatrix), but I have the problem of the stuttering

I am really confused

Advance thank

Reply

Glenn Fiedler June 21, 2007 at 10:38 pm

i think you should try a simple example first, and get your head around it — its not hard! but becomes complex when introducing middleware and “its way of doing things”

here is what i think you need to do with newton, always update it at 60fps (~16.7 ms per frame), but interpolate between according to render rate, as described in the article above

so newton is always creating state for you on integer frame numbers, exactly 1/60th of a second apart, while your renderer is not always doing this, it is working on arbitrary dt, — so you interpolate between the two nearest integer frame samples to find the position/orientation of your body at the render time

cheers

Reply

Cazy June 26, 2007 at 1:46 pm

I am very impressed by the quality of the article too. I’ve read a few more on the subject but none was this clean and eloquent.

One comment though. The interpolation function in your code looks like this:

State state = currentState*alpha + previousState*(1.0f-alpha);

My calculations (and intuition) say it should be:

State state = currentState*(1.0f+alpha) – previousState*alpha;

Am I wrong? Can you double-check your math?

Best regards, Cazy.

Reply

Glenn Fiedler June 26, 2007 at 10:49 pm

interpolation is between two known values, so its “perfect” – just lagged by up to one frame

extrapolation is jerky and is predicting ahead, thus gets it wrong, and has to snap and pop to correct

trust me you want interpolation

take the example source code and change it to extrapolation, and let me know how it goes! – maybe it’ll be good for you, i’m conservative so i prefer interpolation

cheers

Reply

Cazy June 27, 2007 at 12:03 pm

What confused me is that the actual current time is currentTime + acumulator, so it’s outside the (previousTime, currentTime) interval. But after thinking it trough I realised that what you’re doing is shift the fraction alpha back one inteval. This is complelty legal, as the game loop uses a fixed time step. So CurrentState could be vweyt well named NextState and PreviousState could be named CurrentStep.

Thank you for your time, reading your article and replies was very informative. One other question though (feel free to ignore it): why do you initialize currentTime to 0? Isn’t that going to give a wrong deltaTime the first time the game loop is entered?

Best Regards, Cazy.

Reply

Glenn Fiedler June 27, 2007 at 8:30 pm

good point, fixed!

Reply

Glenn Fiedler July 1, 2007 at 5:34 pm

chances are the precision of your timer is probably too low – upgrade to QueryPerformanceCounter and see how it goes

Reply

Gregoris jose July 1, 2007 at 5:15 pm

Hi cheers

I cannot make him to work still, but I think that I am very close.

At the moment, I don’t use QueryPerformanceCounter .
I wanted to ask to you.
How much can this affect in the problem?.

At the moment I has a undersampling problem.
My fps fluctuates between 29 and 35.

Advance thank you

KIKO

Reply

Darklawl September 28, 2007 at 4:38 pm

Great article which nicely describes a solution for a “common” problem!

Reply

Naveen Nattam January 9, 2008 at 11:31 am

I just wanted to give a huge thanks to you Glenn. Your method helped me out incredibly! I have way more control over my physics simulation in my app now! Thanks again!

Reply

Cyde Weys March 10, 2008 at 9:00 pm

Thanks for the great article. You have the optimal solution here that I really wish I had known about when I was screwing around with physics simulation Java applets back in high school. The animation was just never quite right.

Reply

Macguffin May 5, 2008 at 11:41 am

Hi Glen,

That’s an excellent article. Thanks!

Reply

David May 21, 2008 at 6:49 pm

Hi Glenn,

Thank you for this article, as a beginner in game development this is a great help and I will definitely make my game loop like this.

I also like the way you separate your window code from your game code, it makes everything so much more clean.

I got a question though, when I run your example I can still see the dot stuttering from the moment it goes left for the second time and the stuttering stays until it slows down in the middle.
Is that normal? Am I being too picky? Do you have the same effect when you run it or your computer?

Anyway, again, thanks a lot for this.

Regards

David

Reply

Dunge August 11, 2008 at 4:46 pm

I was reading your article and tough it was perfect, but I just though “integrate” meant the physics update/game logic/input pooling and I though it was working this this, but after checking the source code, integrate is really a mathematical integration, and I don’t quite understand what it is doing there. I also don’t quite understand the constants used in the function, and what are x and b are supposed to mean in your State structure..

Reply

admin August 1, 2010 at 9:01 am

Basically integrate just means to advance the simulation state forward. You can try it with something simpler like euler integration, eg. x += dxdt * dt if you like. cheers

Reply

Bob August 11, 2008 at 5:50 pm

For the Windows alt-tab issue, the other solution is to run the physics code even when the renderering code isn’t happening. This should free up the CPU time being used for graphics, and given the technique in the article wouldn’t need to run perfectly smoothly anyway.

This is especially important in multiplayer games where you can’t just automatically pause the game.

Reply

Nick October 4, 2008 at 12:58 am

Glenn,

Absolutely superb writing style you have, man — you definitely have the knack to teach others, and well. Thank you for this brilliant article.

-Nick

Reply

Glenn Fiedler October 4, 2008 at 10:57 am

damian, yes i agree the absolutely correct pattern is a producer/consumer model with the simulation running in another thread or process from the renderer – i’ll be writing a new article about this at some point i hope

Reply

Marcelo November 10, 2008 at 11:21 am

I am a programmer and wannabe-game-developer, and am currently trying to tackle a project that is much larger than my skills. Just ’cause. :)

Being that so, I have to thank you very much on this article, it’s been really helpful. It’s also taken me several hours to wrap my head around the “final touch”. I’ve been able to “free the physics” and, of course, experienced the problem you mentioned.

So here’s how I understand it: In “free the physics”, we are always rendering the latest physics step we have, even though we’re a bit ahead of it in time. On transitioning to “the final touch”, though, we decide to render something that is between the latest physics step and the step BEFORE it. That would mean, as I understand, we’re further away from “the truth” (the state as it would be in current time) than we were before deciding to interpolate, but that means better animation.

Do I understand it correctly?

Thank you again for this,
Marcelo.

Reply

Glenn Fiedler November 10, 2008 at 11:29 pm

yes, you are stepping forward at nice physics intervals like 1/60th of a second, but rendering at another rate – since you have no way to get the exact position at the real time of render, you just interpolate between the two nearest physics steps to get the approximate position at the render time t, so that your rendering is smooth

if you don’t do this, you get temporal aliasing – eg. jittery movement

cheers

Reply

Marcelo November 11, 2008 at 7:53 pm

Exactly, I am getting this exact problem right now.
What was hard for me to “get” was the part that, on the last code snippet, we’re not rendering something that is the latest physics step we know of, we’re rendering 1 dt BEFORE that!

That was kinda weird for me at first, but it makes a little more sense now. As soon as I can figure out how to get/set all of the “state” of the simulation (I am using a framework, Box2D, so it encapsulates the state), I’ll try that and see how it goes. Thanks again!

Cheers,
Marcelo.

Reply

Soj November 26, 2008 at 11:47 pm

It seems to me that with this method there will always be a remainder. It’s unlikely that the time would happen to fit with a multiple of your dt, so you will always be doing interpolation.

You write: “We can use this remainder value to get a blending factor between the current physics state and the previous state simply by dividing by dt”

If you want to interpolate the next point, you should be getting the the blending factor between the current and the next state, not the previous. So to do this interpolation, you have to also calculate the next step, even though you are not yet taking it.

Reply

space November 27, 2008 at 1:31 am

I’ve discovered a problem with this method.

If the computer cannot keep up, meaning it’s been longer since last frame, then you have to calculate several physics states for that frame.

This will mean that this frame will take even longer to calculate for the computer, and thus when you get to the next frame, even more time has passed, and you will have to do even more calculations for that frame, which will take even longer.

It’s an evil spiral, that means once it just gets slow enough once, for the computer to not be able to keep up, then the accumulation will just keep growing bigger every frame.

Reply

Glenn Fiedler November 27, 2008 at 12:22 pm

sure thats actually correct, but the premise of this article is that you can actually afford to simulate one timestep in <= the actual time it is simulating

so in your case, you should simply use a variable framerate, or optimize your code down so it fits in budget

cheers

Reply

Ape-Inago November 30, 2008 at 8:43 pm

if you’ve already got code that can interpolotate a timestamp… if your simulation can’t keep up, you’ll atleast know how much it isn’t keeping up by the accumulator being > than 1/60th (or whatever rate you are intending to get)… and can get a rough interpolotation since the last time.

maybe that didn’t make much sense, but it worked decently enough for me.

Reply

Netherby December 8, 2008 at 7:30 am

Hehe, well if it takes longer than your time step to simulate that amount of time, you’re in a bit of trouble! You probably need to increase the size of your step..

These are some very good articles!

Though I’m slightly baffled by the interpolation used.. You’re dropping back one step then interpolating by alpha towards the most recent known data.. Is that really the best way to handle it? I guess it’s the only accurate data..

Any way I was thinking that having the rendering done in a separate thread would be the best solution, but it adds complexity and makes things harder to debug.. So I was considering going with the single threaded approach for initial revisions and then moving the rendering to another thread.. But do you think this would just cause more pain in the long run than just starting with that approach?

Reply

Glenn Fiedler December 8, 2008 at 6:10 pm

yes i actually prefer the separate thread approach myself, and it has better CPU patterns than the approach in this article, avoiding having to simulate 2 or more sim frames per render frame in the common case, spreading it out properly with frame sleeps — it also avoids the “input aliasing” that you get with this approach, which is subtle, but there

or even better — put the simulation in a different process and connect a “view client” to it, using a simple network model with interpolation/extrapolation

ps. the reason i interpolate previous two frames is to always be accurate, you could extrapolate from the current frame if you want, but this causes discontinuities if the velocity changes abruptly (eg. a bounce…)

cheers

Reply

space December 12, 2008 at 3:43 pm

I see now, that the spiral I mentioned can be avoided by making sure the timestep is big enough. Of course there will be a lower limit of how slow the computer can be then, but you can’t expect your games to work on a 286 anyway :)

I also wondered about the interpolation.

I understand the reason to interpolate and not extrapolate, but it doesn’t make sense though, since the position you are getting is a previous one.

To do the interpolation for the correct position, you should use the current position and the NEXT position, meaning you would have to always calculate the next step, a frame before you actually render it.

Maybe that is what you are already doing, and I just didn’t catch that in your code. I don’t know.

I was also thinking, that your clamp the deltaTime to some max, it would mean that you couldn’t use it for realtime multiplayer games, since one computer could get behind. But I guess it could under all circumstances, since the timers might not run the same on both. I guess in such cases you would need some time signal from the server to keep it accurate. But maybe these differences would be so small that it wouldn’t be important.

By the way, thanks for the article, it was useful for me.

Reply

Glenn Fiedler December 12, 2008 at 4:16 pm

yes thats exactly what i’m doing, interpolating between the previous frame and the current – effectively adding one frame of latency

cheers

Reply

Khu December 30, 2008 at 1:36 pm

Thank you so much! This is awesome! =) I gotta read up on that linear interpolation thingy though.

Reply

Fredrik January 12, 2009 at 3:01 am

Hi,

nice article! Although I’ve been using these techniques for a while, I never thought of it this way. Rather, these are classic client/server game design (client doing rendering, server doing physics and stuff). The interesting part however, that one that threw me a bit off, you interpolate between last and current frame (effectively adding a frame of latency). Wouldn’t make more sense to extrapolate (sometimes called prediction) from the current frame onto the next, and compensate when the frame is finished? The reason for this is two-fold, one, as you describe, to smooth the animation, and two (which is more important if you’re a network jock like me) to compensate for packet loss.

Reply

Glenn Fiedler January 19, 2009 at 6:54 pm

in this case there is no need to extrapolate, since the rendering is performed synchronously with the simulation in one process – of course, if you had a server process running the simulation and a client process viewing it, then yeah it would make sense to have support for extrapolation

Reply

Vorn February 3, 2009 at 9:02 pm

I am curious: how does one handle interpolation of objects that do not exist in one frame or the other? for instance, a bullet only exists in the frames between being fired and hitting its target. Does one simply not display these objects? Or would something more involved be preferable?

Reply

Glenn Fiedler February 3, 2009 at 11:12 pm

if an object is created, you just set its previous position same as the current, eg. dont interpolate

if the object is deleted, then obviously you dont need to interpolate it because its no longer there

of course, to be smooth about it fade-in fade-out works fine, during which time you’d interpolate normally

cheers

Reply

Sirius February 5, 2009 at 12:08 pm

Ah, works perfectly!
Also, thank you for your advice on fast forwarding, makes sense too. :)

Thank you very much for your help~!

Cheers~!

Reply

Daniel SL April 7, 2009 at 6:32 am

You’re fuckin fantastiiiiiic! Haha

This article really save.. Only 2 words: THANK YOU!

Greetings from Argentina,
Daniel SL

Reply

Mc Jman July 28, 2009 at 2:31 am

Sorry, but I’m having a bit of trouble implementing this in obj-c
I ported the code from the download example you provided and my version compiles and returns results, but the values seem way off.

One method in particular has me wondering….

float acceleration(const State &state, float t)
{
const float k = 10;
const float b = 1;
return – k*state.x – b*state.v;
}

Why isn’t the value of “t” used in this function?

Thanks

Reply

Glenn Fiedler July 29, 2009 at 10:15 am

the value t is not used in that function, it is just passed in in case you want an acceleration that is a function of time, eg. sin(t) – in this case, acceleration is just a function of distance from the center point and velocity (it is a simple damped spring)

cheers

Reply

sigzegv August 23, 2009 at 12:54 pm

Great article, thank you very much.

Just to be sure ( i am new in game development ), if I understand, any code writen inside the ‘while( accumulator >= dt )’ is totally independant from framerate, is that right ?
So is this the good section to implement any game mechanics that have nothing to do with rendering ?

Reply

Glenn Fiedler August 23, 2009 at 1:06 pm

precisely, the game simulation update goes inside the while loop – anything which is per-render frame goes outside – eg. perhaps you have some visual only particle effects, these could be updated at render frequency if you wish

Reply

quano September 3, 2009 at 12:31 pm

Awsome article. I’ve implemented this in my game and it works splendidly!

Reply

Glenn Fiedler September 3, 2009 at 3:12 pm

cool, glad you like it – cheers!

Reply

Quincy September 16, 2009 at 3:24 am

This may sound very dumb but what is state ?

Reply

Glenn Fiedler September 16, 2009 at 10:30 am

state is the current attributes of a body in the simulation

for example for a rigid body state is position, velocity, orientation and angular velocity

for a car, state could have all of that information but also include the RPM of the engine, the current gear, the suspension lengths for each wheel, the speed of each wheel rotating and so on

basically, state is the thing which you step forward by delta time (dt) each step of your simulation

cheers

Reply

Mike M November 20, 2009 at 4:37 am

You are a gentleman and a scholar.
Many thanks for this guide!

Cheers!

Reply

Ilya February 17, 2010 at 4:00 pm

Many thanks for writing this wonderful article!

Thanks to it physical simulation in my game now runs much smoothly than ever before!

Reply

Anonymous February 21, 2010 at 5:14 pm

Glenn Fiedler :
to take it even further, you can run the main physics loop entirely on a separate thread which actually runs (in real time) at the number of frames per second the physics should run (say 100hz) and the render thread just reads latest physics state and interpolates, completely independent of physics
this way you are never doing two or more physics updates per-update, so processing is more evenly distributed
in addition, if you gather the input for you simulation on the physics thread, you sample the joystick or keyboard at regular 100hz intervals, which leads to better behavior of your physics
consider this, “fix your timestep version 2.0″

Hi Glenn, thank you for such a beautiful article, nicely done!
I implemented a testbed with box2d and i have the renderer running in the main thread, while the physics and input are running on another one: i’m experimenting the better way of doing things and at this point i can say from my tests that a strict producer/consumer model (that is, a frameNeeded semaphore and a frameReady semaphore) make the physics thread fluctuate since it’s need to wait for the render thread to signal a frameNeeded.
However, implementing it with a mutex protecting the “onRender” call (main thread) and the same mutex protecting the “onUpdate” call (in the other thread), adding “usleep” to avoid both threads concurring much for the lock seems to work flawlessly.
The thing i can’t get to work is the render thread to do subframe interpolation: i mean, everything is fine if the update thread do the subframe interpolation/time aliasing lerp, but if it would work in the render thread as you said it may need less cpu time if vsync is on.
Anyway, let me know if i can send you my code for your own tests: i see you are planning a “fix your timestep v2″ so i’m willing to help you out, although i’m running Ubuntu it shouldn’t be a problem to make v2 cross-platform!

Reply

Manuel Bua February 22, 2010 at 4:30 pm

Oh well, i got it fixed, i wasn’t interpolating the correct values due to a bad git commit..

Reply

Manuel Bua March 3, 2010 at 3:03 am

I forgot to mention in your sample code you are also interpolating the velocity, not only the screen position: obviously you intended to interpolate the screen state with properties like position, rotations and scaling, but this may lead other people to think they need to do the same with other forces, as well as trying to inject these lerp’ed values back in their physics engine.
I was reading Box2D forums and some code around and, sadly, most of them seem to misunderstand this very important point: too bad since it’s a very well-written article on a too much often undervalued subject.

Reply

Glenn Fiedler March 4, 2010 at 12:37 am

You are correct in that the velocity does not need to be interpolated. The code interpolates the entire physics state for the object but in fact the only interpolated quantity which is actually used is the position.

Reply

ioio March 29, 2010 at 11:58 pm

at this point, when running the integrate function in the physics loop, is this call completely CPU independant ? I understand we are independant from rendering, but are we independant from cpu speed for simulation ?

Reply

Glenn Fiedler March 30, 2010 at 10:39 am

I’m not really sure what you mean. Yes it’s CPU independent, to a degree assuming you can simulate one physics step of dt in less than dt/2 in real-time, you should be fine. Otherwise you may get spiral of death given that you may have to simulate 1-1-2-1-1-2 etc. to speed up occasionally when the sim rate is lower than the render rate. Alternatively, you could move the sim into it’s own thread or process to be completely asynchronous to render.

Reply

Jamie March 30, 2010 at 11:58 am

Excellent article. It is hard to find such clearly written material regarding game physics. Great job :)

Reply

Glenn Fiedler March 30, 2010 at 12:40 pm

Thanks! Ironically, it’s the very first article I wrote waaaaaay back in 2004… and it’s still the most popular. Despite many attempts to improve my writing style. I should just give up. This article is always 2x more hits each day than any other =)

Reply

Carlos Hernandez April 16, 2010 at 9:07 am

Nice article. I have developed a game for the iPhone, and the game renders and it is played beatifuly on an iPhone 3GS or 3rd generation iPod touch, but on older hardware it starts fine, but at some point on the game, especially when loading textures, and because of memory constraints, I need to start clearing the image cache, and that eventually lowers my fps, after a few seconds everything comes back to normal. But the thing is, that under those few seconds, some objects that were falling, suddenly they appear on the ground, and the point of the game is to kill this objects in mid air. So my question is, do you think that implementing the rendering interpolation and/or having the calculations and rendering algorithm on different threads might eliminate this problem? I have implemented the fixed time step, but not the rendering interpolation. Here is the link of the game to give you an idea: http://www.softwarefactoryllc.com/airassault

Thanks.

Reply

Glenn Fiedler April 17, 2010 at 12:39 am

you could move the texture loading and other stuff onto a separate thread so they don’t hitch up the simulation – this is the best way to get around your problem. interpolation as described in this article won’t help you. moving the sim off to a separate thread is another way to look at it, but i’d first try getting the loading async – cheers

Reply

Carlos Hernandez April 20, 2010 at 10:53 am

Thanks for your response. I tried all the solutions, but what really did the trick was clamping the dt values to 0.1. Now the game is super responsive in any situation on all devices, and even if it gets slow, at least the physics and rendering engines are in sync always.

Thanks for a great article, and for taking the time to clear my doubts.

Reply

KIVagant May 17, 2010 at 3:12 pm

Hello.
Can you help me, please? I need to solve a simple problem.
I created a cube (JBox or Cube). The cube fly from same top point and then rolling on the plane. How can I make, that cube always stopped the same one side up?

Sorry for my bad English.

Reply

Glenn Fiedler May 17, 2010 at 5:55 pm

this is actually very hard, i remember a paper about something pixar did for Monster’s Inc where they ran a solver to solve motion for rigid bodies to pass through various points and end up at a specific configuration (e.g. one side up)

i would say that you should try to find this paper and read about how they do it

Reply

Gregory Defaisse May 19, 2010 at 8:13 am

Thanks for the article I get my timestep fixed !

But for those you think it’s a bit complex to use a coefficient to calculate the exact position of all their physic objects and than it complicate the calculate and codes, I found a simple solution costing only some part of 1 frame and doing the same exact result.

In fact you just have to to wait some milliseconds to have a round count of frames, for example, your render function took 88ms and your physics frame is fixed to 10ms then you wait 2ms and calculate the number of physics frame to do (88+2)/10 -> 9 you proceed and render again, so simple!

Reply

mariusz j May 25, 2010 at 2:25 pm

Hi,
Thank you for great article!

I have on remark, though.
I think that it would be better, if instead of following condition:

while (accumulator>=dt)

you’ve used:

while ( !( accumulator < dt ) )

Comparing if two floats are equal can get you into trouble.

Reply

Glenn Fiedler May 25, 2010 at 5:37 pm

i agree that checking if two floats are equal is very bad, but as far as I can tell conditionals you presented are exactly equivalent:

bool a = accumulator >= dt;
bool b = ! ( accumulator < dt );
assert( a == b );

(try this and let me know)

of course, bool c = accumulator == dt;

is craziness…

Reply

Glenn Fiedler May 25, 2010 at 5:39 pm

also for what its worth, using a float value to accumulate time t from dt is also craziness, please consider that you should have some 64bit fixed point representation of time if you use this technique, otherwise the precision of your time t gets worse the longer your program runs. i only use float here for clarity because i use it for the dt and accumulator only. if you have a truly fixed timestep, then you can use your integer frame count as time

Reply

David June 9, 2010 at 5:00 am

Great article.

Only problem I encountered was instances of negative deltaTime (which made the dot animation vibrate as it moved). Apparently this can sometimes happen on duel-core CPUs. Easy way around this was to simply add another loop to update deltaTime until it is positive again (ignoring it basically).


float newTime = time();
float deltaTime = newTime – currentTime;
while(deltaTime < 0){
newTime = time();
deltaTime = newTime – currentTime;
}
currentTime = newTime;

Reply

Manuel Bua June 11, 2010 at 1:01 pm

@David
Don’t use time(), it will be wrong on multicore processors: if available, use monotonic time.
On *nix systems you can use “clock_gettime( CLOCK_MONOTONIC, …” and linking with -lrt

Reply

George Stagas June 29, 2010 at 5:34 am

You are fantastic! I was having a really hard time getting a Javascript physics animation to work smoothly and accurately on all browsers/all systems, and your solution fixes everything and required minimal coding to implement! The interpolation kicks ass, I can now do super slow smooth motion just by changing a variable! It’s great for replays etc. and keep everything consistent among browsers and their crappy timings. Thank you!

Reply

Erwan June 30, 2010 at 8:30 am

Hi ! I find these articles on physics very useful.
I wanted to ask Glenn a question:
If I had to buy a game’s physics book which one would you recommend ?
I am looking for something that covers the basics and provides solid tools such as the ones presented in your articles.

Thank !

Reply

Glenn Fiedler June 30, 2010 at 9:58 am

I recommend:

“Essential Mathematics for Games and Interactive Applications, Second Edition: A Programmer’s Guide” by James M. Van Verth and Lars M. Bishop

“Real Time Collision Detection” by Christer Ericson

Also, the siggraph course notes by Baraff are a great introduction to physics simulation.

Reply

Erwan July 1, 2010 at 3:42 am

Thanks a lot, I’ll try “Essential Mathematics for Games and Interactive Applications, Second Edition: A Programmer’s Guide”

Reply

Gregor July 17, 2010 at 1:47 am

siggraph course is brilliant, thank you

Reply

Gregor July 16, 2010 at 3:53 am

Great tutorials, thanks for taking the time to write them!

What if the update frequency was dynamic as in per computer or per scene change or even per fps drop. Take for example a simple game which fps will vary a lot (from 30-400fps on different computers). Would changing the physics update step help the game at all and when should it be done if its not in the physics initialization (after updates were done on the objects).

Reply

Glenn Fiedler July 16, 2010 at 9:13 am

if your game physics is mostly simple linear motion, you’ll probably get no real benefit. if you have more complex physics you’ll benefit from more consistent behavior with fixed timesteps.

so, work out how differently your game sim code behaves depending on framerate and if it’s significant or problematic then fixing the timestep is a good idea. some examples of where this is good, tunneling at low framerates if you don’t raycast, different behavior of springs at different delta time due to integrator errors etc.

Reply

AngleWyrm January 31, 2010 at 12:08 pm

Could you please explain a little bit about why n steps of dt is often different from one step of n*dt?

Reply

Glenn Fiedler January 31, 2010 at 1:25 pm

In general, physics simulation is too complicated to solve analytically so it is solved via numerical integration. Numerical integration is an approximation to the exact solution in which the accuracy of the result depends on the size of time-step. Typically numerical integration gives more accurate results for smaller time-steps. It follows that one step of n*dt is not the same as n steps of dt.

Reply

Glenn Fiedler July 15, 2010 at 9:18 pm

you can interpolate, you can extrapolate — if you interpolate you’ll add *up to* one frame of latency depending on how much accumulator you have left. the alternative is to extrapolate forward networking style and trade latency for misprediction

cheers

Reply

Gaute Løken July 15, 2010 at 11:43 pm

With your code you’re interpolating between the states that happened the current state (which happened some accumulator time ago, and previousStep which happened 1 dt + accumulator time ago. So by interpolating the state at previousTime + accumulator you’re rendering the interpolated state at exactly 1 dt behind rendertime, not up to 1 dt.

With my proposed method I would interpolate like you, but on a predicted state rather than the two previous states. What I’d like to know is why one method would be preferable to the other, or if you’d think the way I propose would be feasible/reasonable.

Reply

Glenn Fiedler July 16, 2010 at 9:15 am

either way is good and it depends on the error you consider most acceptable during a sharp change in velocity – consider a particle moving very quickly and bouncing @ 45 degrees, cheers

Reply

Leave a Comment