Fixed timestep + Box2D game loop

Started by
1 comment, last by tookie 9 years, 12 months ago

Hello!

I'm working on a 2D platformer. I have good experience with C++, but not much experience using the Box2D physics library.

I've read the famous "Fix your timestep" method, and it seems the way to go.

This is my implementation:


const int updateFPS = 30;
const float dt = 1.0f / updateFPS;

float elapsedTime = 0.0f;
float accumulator = 0.0f;

Uint32 currentTime = SDL_GetTicks();

while (!quit)
{
    // Process system events here...

    const Uint32 newTime = SDL_GetTicks();
    float frameTime = static_cast<float> (newTime - currentTime) / 1000.0f;

    // Avoid spiral of death
    if (frameTime > 0.25f)
        frameTime = 0.25f;

    currentTime = newTime;
    accumulator += frameTime;

    // Logic update
    while (accumulator >= dt)
    {
        cout << "Integrate step, t = " << elapsedTime << endl;
        elapsedTime += dt;
        accumulator -= dt;
        // Update game entities
    }

    const float alpha = accumulator / dt;
    // Render code.....
}

I have some doubts...

1) Where should I call the Box2D world update function? inside the "Logic update" loop or inmediately after/before it?

2) Do I really need 60 FPS for the physics? This game will not have lots of collisions per frame, and I'm not using "bullet" bodies.

3) Is this method needed in all the game states? For example, should I use this fixed timestep code in the main game menu, in the credits, etc?

Thanks, Paul.

Advertisement

Good choice going for the fixed time step. To answer your questions.

1) You want to update Box2D inside the Logic update loop. Use 'dt' as the timestep in world.step()

2) Experiment with the physics time step and see what works best for you game. There isn't one right answer for all games.

3) No, you don't need to use a fixed timestep for those things, but why wouldn't you? Adding two types of udpates adds unneeded complexity to your code.

My current game project Platform RPG

Thank you HappyCoder!

This topic is closed to new replies.

Advertisement