Well lets say you are running box2d. Then you'd need some sort of loop to step through and update the physics. So a scheduled method is a perfect example for that. Let's say the scheduled method run's as fast as it can, called 'tick'.
Let's follow my thought process here. And actually by doing so you'll fix the timestep and understand what's going on....I hope ;)
So I call box2d's Step in my loop.
- (void) tick:(ccTime) dt
{
box2dworld->Step(dt, vIterations, pIterations);
}
box2D: You can't do that Davey... I mean Lam.
What?! Why not! Oh my... what's going on with the collisions it's all crazy.
box2D: Variable time-step? Are you trying to give me a heart attack!
hmm... box2d likes a fixed timestep.
box2D: Yes.
Ok that's a little too weird no more conversations with you...
So fixed timestep huh... ok let's do this instead.
#define kFixedTimeStep 1.f/30.f
- (void) tick:(ccTime) dt
{
box2dworld->Step(kFixedTimeStep, vIterations, pIterations);
}
But now I start getting anxieties and butterflies in my stomach.
What happens if kFixedTimeStep < dt?
It will never catch up with my program. It will always lag behind because it's fixed. A runner that won't increase his speed to keep up with the rest will get further and further away. =(
What happens if kFixedTimeStep > dt?
It will be too fast. It shouldn't of called step at all maybe it should've waited until the program caught up, then we can simulate. =(
So what to do? Why don't we accumulate dt until it's bigger than the fixed timestep. Call our step and since we used a bit of our accumulation, we remove a fixed step from the accumulation to compensate. All variables with an underscore at the end are assumed to be class variables.
#define kFixedTimeStep 1.f/30.f
- (void) tick:(ccTime) dt
{
accumulation_ += dt;
while(accumulation >= kFixedTimeStep)
{
box2dworld->Step(kFixedTimeStep, vIterations, pIterations);
accumulation_ -= kFixedTimeStep;
}
// Do cool gameloop updates below.
}
So now accumulation fixed everything! Accumulation prevents steps from calling too fast and if we've accumulated too much we call multiple steps to catch back up!
It's perfect! It's awesome!
"Disclaimer: The code presented above is in no way 'perfect' or 'awesome'. It was written here without actual testing."
I hope that made some sense.
And fix your timestep!