• Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

# Framerate independent friction

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

36 replies to this topic

### #1BradDaBug  Members   -  Reputation: 841

Like
0Likes
Like

Posted 28 April 2012 - 07:22 PM

I noticed that my game runs a bit differently when running at 60 FPS on my PC and 30 FPS on my phone, and I traced it down to the friction code. I'm applying friction like this:

`newVelocity = oldVelocity - oldVelocity * friction * elapsedTime`

The results are not consistent between 60 Hz and 30 Hz. But then I thought about how continuous compound interest is calculated, and I came up with this:

`newVelocity = oldVelocity * exp(-friction * elapsedTime)`

It works perfectly, at least on paper. Has anyone else ever used an approach like this? Or is there a better way to do it?

Edit: I should mention that the game is using a fixed time step. At 30 Hz it's 1/30 seconds and at 60 Hz it's 1/60.

Edited by BradDaBug, 28 April 2012 - 07:24 PM.

I like the DARK layout!

### #2Álvaro  Members   -  Reputation: 5895

Like
1Likes
Like

Posted 28 April 2012 - 10:50 PM

I think the better way to do it is to use a fixed time step for physics, independent of how fast the screen updates.

http://gafferongames.com/game-physics/fix-your-timestep/

### #3jefferytitan  Members   -  Reputation: 1006

Like
0Likes
Like

Posted 28 April 2012 - 11:07 PM

Personally I think fixed timestep physics is good, but some accomodation for varying time delta is nice because schedulers are never 100% precise.

### #4SimonForsman  Members   -  Reputation: 3715

Like
0Likes
Like

Posted 28 April 2012 - 11:41 PM

Personally I think fixed timestep physics is good, but some accomodation for varying time delta is nice because schedulers are never 100% precise.

what do schedulers have to do with a fixed timestep ?

If you use a fixed timestep you won't use elapsed time in the physics calculations.

updatePhysics(elapsedTime);

you do:

while (elapsedTime>timeStepSize) {
updatePhysics(timeStepSize);
elapsedTime-=timeStepSize;
}
where timeStepSize is constant so the physics calculations will be deterministics as you always give it the same delta to work with and instead call the physics update routine multiple times per frame if needed (or not at all if your framerate is higher than the physics update rate)

Edited by SimonForsman, 28 April 2012 - 11:44 PM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

### #5japro  Members   -  Reputation: 774

Like
0Likes
Like

Posted 29 April 2012 - 04:28 AM

It works perfectly, at least on paper. Has anyone else ever used an approach like this? Or is there a better way to do it?

It's the correct way of doing it... You are essentially multiplying with (1-friction) every time step so over multiple time steps the "correction" is (1-friction)^n and not n*(1-friction) (1-n*friction) as you would get with the first version when increasing the timestep n times.

Edit: n*(1-friction) would be totally off

Edited by japro, 29 April 2012 - 04:57 AM.

### #6jefferytitan  Members   -  Reputation: 1006

Like
0Likes
Like

Posted 29 April 2012 - 04:09 PM

what do schedulers have to do with a fixed timestep ?

Say for example your physics engine runs at 50Hz, so 0.02s between executing physics. Due to the nature of a multitasking OS it won't be precisely 0.02s every time. One time it might be 0.018, another time 0.023. The difference may not be visible... or it may. Depending upon the nature of the physics and the speed of the objects involved. Also ignoring varying delta would be bad if there was a requirement for repeatability, such as in MMO games.

Using some game platforms the timing variation may be minimal, but some systems that I've tinkered with can have variations of up to 20%.

### #7SimonForsman  Members   -  Reputation: 3715

Like
0Likes
Like

Posted 29 April 2012 - 04:37 PM

what do schedulers have to do with a fixed timestep ?

Say for example your physics engine runs at 50Hz, so 0.02s between executing physics. Due to the nature of a multitasking OS it won't be precisely 0.02s every time. One time it might be 0.018, another time 0.023. The difference may not be visible... or it may. Depending upon the nature of the physics and the speed of the objects involved. Also ignoring varying delta would be bad if there was a requirement for repeatability, such as in MMO games.

Using some game platforms the timing variation may be minimal, but some systems that I've tinkered with can have variations of up to 20%.

When you use a fixed timestep the delta is constant, you don't pass the actual elapsed time to the physics subsystem. (if you run the physics at 50hz with a fixed timestep you always pass 0.02 as the delta, if the elapsed time is 0.023 you still pass 0.02 as the delta and carry the 0.003 you have left (so the next update triggers after an additional 0.017s have passed), Therefore the scheduler has no impact on the simulation. (You can even run the simulation without measuring the actual elapsed time if the result doesn't have to be displayed in realtime (if you're making a movie for example))

If you need to compensate for a variable delta then you're not using a fixed timestep, you're using a variable timestep.

Edited by SimonForsman, 29 April 2012 - 04:50 PM.

I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

### #8Cornstalks  Moderator*   -  Reputation: 5411

Like
0Likes
Like

Posted 29 April 2012 - 04:44 PM

Say for example your physics engine runs at 50Hz, so 0.02s between executing physics. Due to the nature of a multitasking OS it won't be precisely 0.02s every time. One time it might be 0.018, another time 0.023. The difference may not be visible... or it may. Depending upon the nature of the physics and the speed of the objects involved. Also ignoring varying delta would be bad if there was a requirement for repeatability, such as in MMO games.

Using some game platforms the timing variation may be minimal, but some systems that I've tinkered with can have variations of up to 20%.

Pseudo-code for which the scheduler doesn't matter:
```float timestep = 1.0f / 30.0f; // 30 updates per second
Clock clock;
clock.start();

while (runMainLoop)
{
if (clock.time() >= timestep)
{
clock.reset();
updateGame(timestep); // use the *fixed* timestep
}

renderGame();
}
```

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

### #9jefferytitan  Members   -  Reputation: 1006

Like
0Likes
Like

Posted 29 April 2012 - 05:02 PM

@Cornstalks: Very true. I wonder whether it might appear inconsistent or stuttery to a player when physics performed is constant but the real-time that it occurs in is not constant, but I really have no proof either way.

### #10Cornstalks  Moderator*   -  Reputation: 5411

Like
0Likes
Like

Posted 29 April 2012 - 05:19 PM

@Cornstalks: Very true. I wonder whether it might appear inconsistent or stuttery to a player when physics performed is constant but the real-time that it occurs in is not constant, but I really have no proof either way.

True. In a well done game, the rendering is often interpolated. So you don't just naively call renderGame(), but you give it the system time as well and it interpolates the rendering between the current system time and the game time.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

### #11Álvaro  Members   -  Reputation: 5895

Like
0Likes
Like

Posted 29 April 2012 - 05:54 PM

You could read the link I posted, which explains exactly what fixing the timestep means, including interpolation. Just saying.

### #12Cornstalks  Moderator*   -  Reputation: 5411

Like
0Likes
Like

Posted 29 April 2012 - 06:00 PM

You could read the link I posted, which explains exactly what fixing the timestep means, including interpolation. Just saying.

I figured he didn't read it, so I'd summarize it here

@jefferytitan: Everything I've said in this thread comes from what alvaro linked to...
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

### #13jefferytitan  Members   -  Reputation: 1006

Like
0Likes
Like

Posted 29 April 2012 - 06:27 PM

You could read the link I posted, which explains exactly what fixing the timestep means, including interpolation. Just saying.

Nice article. I wish I'd had time to read it earlier. Work is inconsiderate like that.

### #14MrRowl  Members   -  Reputation: 1084

Like
0Likes
Like

Posted 01 May 2012 - 11:20 AM

Your exponential form will give you timestep independent behaviour.

However, it's not correct for (what's usually called) friction, since the dry frictional force is independent of velocity. You'd normally call a force or acceleration that's proportional to the velocity, damping (e.g. a damped spring, and your equation is exponential damping). Aerodynamic drag results in the force/acceleration normally being approximately proportional to the velocity squared.

If you want more realistic friction - e.g. for one object sliding on top of another, then calculate:

- The force normal to the contact plane, Fn

- The maximum force that can be generated by friction Fmax = Fn * frictionCoefficient

- The force that would bring the relative tangential velocity v to zero in the following timestep dt: F0 = m * v / dt if your object is a point mass, or if you're apply the frictional force at its centre of mass, assuming you're using Euler integration.

Then you apply minimum(Fmax, F0) - though you need to get the signs right! Comparing Fmax with F0 means that the friction won't cause oscillation when the velocity is very small.

### #15L. Spiro  Crossbones+   -  Reputation: 5187

Like
0Likes
Like

Posted 01 May 2012 - 08:10 PM

Here is more information on fixing your time step that may be of use—maybe save you from falling into a few potholes.
http://lspiroengine.com/?p=378

Fixing your time step will solve all of your problems, but only if done correctly.

L. Spiro
It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

### #16MrRowl  Members   -  Reputation: 1084

Like
0Likes
Like

Posted 02 May 2012 - 05:27 AM

Fixing your time step will solve all of your problems, but only if done correctly.

I disagree If your code is written correctly, and implements good approximations to the real world, then it will handle variable timesteps, to within the approximations. It won't behave exactly the same with different sized timesteps, but the difference will just depend on how good your approximations are. It might be that you find that the variation in frame to frame of the approximation is just too much to put up with, in which case you can, if you wish, decide to use a fixed timestep and run multiple physics steps per render frame*. However, I'd maintain that it's better to start out with a physics system that is capable of handling a variable timestep (because that will likely expose incorrect implementations - like the OP saw), than to start with a system that is locked to one timestep (because that will cover up incorrect implementations).

Also, fixing the timestep won't solve the problem, if the problem is that the friction model is wrong!

Some games use a fixed timestep, and some a variable timestep. There are advantages and disadvantages to both choices.

* Another option might be: If you find your physics goes bad when dt > maxDt, you could split your physics update into N iterations such that dt/N < maxDt (choose N as small as possible!). This will result in the physics sim staying within the good-approximation range, without having to do interpolation between physics frames, or having the physics update time != render update time.

### #17japro  Members   -  Reputation: 774

Like
0Likes
Like

Posted 02 May 2012 - 06:03 AM

A variable timestep introduces stability issues (as in numerical stability). Especially if there is any sort of collision involved...

### #18MrRowl  Members   -  Reputation: 1084

Like
0Likes
Like

Posted 02 May 2012 - 07:27 AM

A variable timestep introduces stability issues (as in numerical stability). Especially if there is any sort of collision involved...

Only if you're solving collisions with spring-dampers (but nobody really does that these days, do they?). In a rigid body simulator, handling collisions with impulses, I don't see any reason why a variable timestep would lead to numerical instability*, as the collisions get handled outside of the integration of the equations of motion (because collisions introduce a discontinuity, and the response is independent of timestep).

Large timesteps can lead to jitter/approximation problems, but that's not numerical instability, or the same as variable timesteps.

Explicit spring/dampers are unstable at large timesteps (depending on the spring/damping values), but that's not the same as saying they're unstable with variable timesteps. Implicit formulations should be stable at large timesteps.

Fixed and variable timesteps have both got advantages and disadvantages - I'm just saying it's best to understand them rather than saying one is always better than the other, or saying that one always leads to problems, or that one will solve all your problems.

* Small timesteps can lead to problems if using Baumgarte stabilisation, where solver errors are corrected by introducing a bias that looks like error/timestep. This can be especially bad with a variable timestep: if a large timestep on one frame results in poor solver convergence, which is then "corrected" on the next frame with a small timestep, leading to excessive correction velocities. However, there are ways to fix this.

### #19Álvaro  Members   -  Reputation: 5895

Like
0Likes
Like

Posted 02 May 2012 - 08:02 AM

I don't think it has been mentioned, but fixed timesteps allow easier reproduction of the results of the simulation, which can be really helpful in debugging. I imagine it also makes synchronization in multi-player games much easier, since there is a common discretization of time, although I don't have any real experience with that.

I can't think of any disadvantages of fixed timesteps. You mentioned something about using a fixed timestep masking problems, but I can't see that as a real problem. MrRowl, do you care to provide other disadvantages?

Edited by alvaro, 02 May 2012 - 08:03 AM.

### #20MrRowl  Members   -  Reputation: 1084

Like
1Likes
Like

Posted 02 May 2012 - 08:35 AM

fixed timesteps allow easier reproduction of the results of the simulation

Indeed!

I can't think of any disadvantages of fixed timesteps. You mentioned something about using a fixed timestep masking problems, but I can't see that as a real problem. MrRowl, do you care to provide other disadvantages?

Here are some:

1. If you use a fixed physics timestep but a variable render frame time (or a render frame time that isn't a multiple of the physics timestep), but don't interpolate the physics results, then a smoothly moving physics object will not move smoothly across the screen, as sometimes it will experience N updates, and sometimes N+1 (for a fixed render frame time).

2. If you do interpolate between physics frames

2.1 that's an additional cost (which might be significant if you've got a lot of objects),

2.2 Also there's some "uncertainty" about where the object is - so when a user shoots an object, where is the impulse applied?

2.3 Debugging might be fun if your debug points etc don't match up with the interpolated object positions

2.4 If the ratio between the physics timestep and render timestep is such that sometimes you run 2 physics steps, and sometimes 1 (for example), and the physics simulation time is significant, then the frame rate can jitter from frame to frame (a lower, but rock steady, framerate is likely better than a high but variable framerate). If there's a spike in the render frame time (e.g. due to disk access), then a fixed physics timestep will result in a spike in the next frame time etc.

3 If the game allows running in slow motion (bullet time) you need to handle at least two, possibly very different timesteps, and the transition between them, otherwise either (a) you always update at the normal timestep, and the effects of interpolation will become obvious, or (b) you always run at the reduced timestep, with a cost that's excessive when running at the normal rate.

In my current home project (a flight sim for mobile devices), a smaller timestep always results in better physics quality. I just clamp the frame time to a max value (something like 0.1s), and always use N physics steps per frame. The user can choose N as a simulation quality setting - it's always at least 3 (or so). This way I get a constant physics simulation cost, so a really steady frame rate (depending on other stuff!), and I can check that everything will at least remain stable at the the maximum physics step time (0.033s). Faster devices get slightly better physics quality. This was originally my quick placeholder before moving to fixed physics timestep and interpolation (which I've done before), but actually I think it works great so don't intend to change!

I know some big commerical games use fixed, and some variable physics timesteps. There are problems to solve whichever way you go!

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS