• Advertisement
Sign in to follow this  

Proper framerate-independent game loop

This topic is 1987 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello there!

I'm working on a game where I use this basic game loop design:

[source lang="cpp"]int main ( int argc, char* argv[] )
// main entry point
{
Load ( );

while ( window->IsActive ( ) )
// game loop
{
// update the ticks for this and the last frame
last_frame_tick = this_frame_tick;
this_frame_tick = SDL_GetTicks ( );

// update the scene depending on how long
// it has been since we last updated
Update ( this_frame_tick - last_frame_tick );

// render the scene
Render ( );
}

Destroy ( );

return 0;
}[/source]

So I update and render the scene as much as possible (with VSYNC off). SDL_GetTicks ( ) is an API function that returns the number of milliseconds that have passed since the API (ie. the game) started. In my Update ( float time ) function, I then multiply every speed (that is, a bullet moving forward for example, but also a character turning their head to one side) by that time.

In theory, this should give me a framerate independent gaming experience - if we're running on an older machine, we might just get 20 fps so the time it takes to render each frame is 50 ms, on a modern machine we could get 200 fps (5 ms per frame). A bullet moving forward at an original speed of 2.5 units per frame will move at 2.5 * 50 = 125 units per frame on the slow machine and 2.5 * 5 = 12.5 units per frame on the fast one. In 1 second, on the slow machine (since it renders 20 fps) the bullet will have moved 125 * 20 = 2500 units total, on the fast one (at 200 fps) 12.5 * 200 = 2500 as well. No matter what speed the computer can run the game at, all the action will always be going on at the same rate, it's just going to look and feel a lot smoother on a better system for obvious reasons.

This is the (very basic) theory from what I understand reading tutorials such as this one. But for some reason, this doesn't work for my games, when I set everything up as explained, my bullets (etc.) will still move a lot faster with a higher framerate!

[source lang="cpp"]// in Update ( float time ):
// GetForward ( ) returns a normalized forward vector for the projectile
bullet->SetPosition ( bullet->GetPosition ( ) + bullet->GetForward ( ) * 2.5f * time );[/source]

What am I doing wrong or misunderstanding here? Is the entire game loop design faulty? The article linked makes it sound like this should work (albeit saying that speed prediction methods are better, stuff I'd rather not get into without it being necessary).

Any help would be greatly appreciated, as always! I'm lost! smile.png Edited by d k h

Share this post


Link to post
Share on other sites
Advertisement

http://gafferongames...-your-timestep/

Read this until your understand it.

He isn’t trying to decouple his logic and rendering, only make logic non-framerate dependent.


Print the values for this_frame_tick, last_frame_tick, and time.
Note that SDL_GetTicks() returns an unsigned integer in milliseconds and you need a proper conversion to float.


L. Spiro

Share this post


Link to post
Share on other sites

Print the values for this_frame_tick, last_frame_tick, and time.


Will do and edit results in in a second.



Note that SDL_GetTicks() returns an unsigned integer in milliseconds and you need a proper conversion to float.


I'm just bruteforcing the conversion as such:

[source lang="cpp"]float time = ( float ) uint_time;[/source]

I didn't consider this a problem, whether the time value is 500 as unsigned int or 500.0f as float? Is this were I'm going wrong?

Thanks for the response! Edited by d k h

Share this post


Link to post
Share on other sites
I second reading that link, it's pretty helpful for this situation. The gist of it is

[source]totalTime = 0;
while(notDeadYet)
{
startUpdate = timestamp();
while(totalTime >= UPDATE_STEP)
{
Update(); // Simulates exactly UPDATE_STEP amount of time each call
}

Render(); // Renders the latest tick
totalTime += timestamp() - startUpdate;
}[/source]

This way at 200 FPS you only update the simulation every X frames, but at 20 FPS you update multiple times a frame as needed. Animations are smoother as you're taking snapshots of a guaranteed smooth stepping, and it's easier to ensure physics are accurate as they're no longer framerate-dependant.

Share this post


Link to post
Share on other sites
I understand the beauty of that game loop design, I'm really just wondering what's wrong with the way I'm trying to do it (where updating and rendering the scene is coupled)! If I can't sort this out, I can always switch to the version with fixed timestep for updating the scene but for now, if possible, I'd prefer to stay with the framerate independent updating and find out what is going wrong. Any further ideas?

EDIT: last_frame_tick, this_frame_tick and time look okay to me. last_frame_tick is 17619 after about 17 seconds, this_frame_tick in the same frame is 17745, time is 127.0f that frame. Next frame, last_frame_tick then is 17745 of course. This looks to be perfectly fine to me! Edited by d k h

Share this post


Link to post
Share on other sites
The problem that you do not realise is that 'you are mixing 2 things into 1 Framerate (FPS) and Rendertime (RT)'.
Looking at your gameloop, I can tell that it is framerate dependent loop. No doubt about that. Why?
- because your update call feeds with the last RT and this RT is produced by an uncapped Framerate. That's why your bullet still travels fast/slow because you are rendering what the last rendertime dictates (rather than what the last update should dictate).

Your framerate should ALWAYS be capped (or fixed) and your rendertime is ALWAYS variable. This last rendertime variance is then broken into steps into your future update calls for the next frame. This is how your loop becomes framerate independent.

Currently, your render call comes immediately after the update call, which is fed with the last render time. This is a typical scenario for framerate dependency. This is why your bullet will still seem to be fast or slow (depending on CPU). To achieve independence you need to do what Firestryke31 or the suggested link said. What he/she posted there is typical scenario for framerate independence.

This method will allow you to cap or fix your framerate (FPS) and allow your render time (RT) to feed into your next update call in steps .
As an example:
you can cap your game loop to always run at 60FPS on slow and fast machines, but your RT will be the one changing. Your updates (logic) will therefore take place in steps as highlighted by Firestryke31 then after those updates you call render.

You cannot achieve framerate independent updates with immediate render call after it, it will never work well across CPUs. You need to break down your updates in steps.

Good luck.

Share this post


Link to post
Share on other sites
First up, you really don't want a framerate independent game loop. Not at all. There are no games out there (okay, benefit of the doubt, less than 1% of games) with a framerate independent game loop. Making your game loop framerate independent puts you at the mercy of floating point inconsistencies and introduces many more problems than benefits.

What you want to do, is choose a framerate for your games update. And ensure your game updates to that time period, whether you choose 30fps update, 60fps update, 120fps update is upto you. This is pretty much as ddlox above me has stated, and how just about every game out there is written. There are implementation differences for sure, but the basic concept is the same.

Whilst that is not the direct answer you requested, the issue you have (looking at the code) is simply doing:


#define MILLISECONDS 1000.0f
float currentTime = 0;

oldTime = timeGetTime();
while ( notDeadYet )
{
newTime = timeGetTime();
timeDelta = newTime - oldTime;

float t = timeDelta / MILLSECONDS;
Update( t );
}



I didn't consider this a problem, whether the time value is 500 as unsigned int or 500.0f as float? Is this were I'm going wrong?[/quote]

The problem is the time is in milliseconds, whereas your float is in seconds. So 500 milliseconds is not 500.0f, dividing by 1000 will not work directly as it is an integer calculation. So the above example uses 1000.0f to force the calculation to use floating point.

I am assuming it is for C/C++, if I made a mistake on that, my apologies.

n!

Share this post


Link to post
Share on other sites
Ah, got it! That was the missing piece of information. I have gone ahead and changed my game loop, Firestryke31's loop did not work out of the box, using the article I came up with this which seems to work fine and caps my update calls (ie. the game simulation) at 50 times a second (every 20ms)!

[source lang="cpp"]// update the scene every 20ms (50 times a second)
const unsigned int UPDATE_STEP = 20;

unsigned int total_time = 0;
unsigned int current_time = SDL_GetTicks ( );

while ( window->IsActive ( ) )
// game loop
{
unsigned int new_time = SDL_GetTicks ( );
unsigned int frame_time = new_time - current_time;
current_time = new_time;
total_time += frame_time;

while ( total_time >= UPDATE_STEP )
{
Update ( );
total_time -= UPDATE_STEP;
}

Render ( );
}[/source]
Does this look better? Works fine from what I can tell! :)

Share this post


Link to post
Share on other sites
Sorry, I forgot to mention that my sample was just pseudocode (and apparently I completely forgot to decrement the accumulated time in the loop).

One thing you might possibly consider is, in a separate "game state," stepping one step into the future, and passing the post-looping [font=courier new,courier,monospace]total_time / UPDATE_STEP[/font] to the renderer to interpolate between the current step and the "future" step, giving smoother animations.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement