Jump to content

  • Log In with Google      Sign In   
  • Create Account


Fixed timestep + Box2D game loop


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.

  • You cannot reply to this topic
2 replies to this topic

#1 TookieToon   Members   -  Reputation: 163

Like
0Likes
Like

Posted 08 May 2014 - 01:02 PM

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.

 



Sponsor:

#2 HappyCoder   Members   -  Reputation: 2608

Like
2Likes
Like

Posted 09 May 2014 - 02:04 PM

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.



#3 TookieToon   Members   -  Reputation: 163

Like
0Likes
Like

Posted 12 May 2014 - 02:33 AM

Thank you HappyCoder!






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