• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
d h k

Proper framerate-independent game loop

11 posts in this topic

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). [i]SDL_GetTicks ( )[/i] is an API function that returns the number of milliseconds that have passed since the API (ie. the game) started. In my [i]Update ( float time ) [/i]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 [url="http://dewitters.koonsolo.com/gameloop.html"]this[/url] 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! [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] Edited by d k h
0

Share this post


Link to post
Share on other sites
[url="http://gafferongames.com/game-physics/fix-your-timestep/"]http://gafferongames.com/game-physics/fix-your-timestep/[/url]

Read this until your understand it.
0

Share this post


Link to post
Share on other sites
[quote name='JWBaker' timestamp='1344954236' post='4969465']
[url="http://gafferongames.com/game-physics/fix-your-timestep/"]http://gafferongames...-your-timestep/[/url]

Read this until your understand it.
[/quote]
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
2

Share this post


Link to post
Share on other sites
[quote name='L. Spiro' timestamp='1344954443' post='4969466']
Print the values for this_frame_tick, last_frame_tick, and time.
[/quote]

Will do and edit results in in a second.


[quote name='L. Spiro' timestamp='1344954443' post='4969466']
Note that SDL_GetTicks() returns an unsigned integer in milliseconds and you need a proper conversion to float.
[/quote]

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
0

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?

[b]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.[/b] This looks to be perfectly fine to me! Edited by d k h
0

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.
2

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:

[code]
#define MILLISECONDS 1000.0f
float currentTime = 0;

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

float t = timeDelta / MILLSECONDS;
Update( t );
}
[/code]


[quote]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!
1

Share this post


Link to post
Share on other sites
Hmmm, can I not edit a post on here? The sample code is, ofcourse, missing a "oldTime = newTime;".
0

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! :)
1

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.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0