The game loop is the heartbeat of every game, no game can run without it. But unfortunately for every new game programmer, there aren’t any good articles on the internet who provide the proper information on this topic. But fear not, because you have just stumbled upon the one and only article that gives the game loop the attention it deserves. Thanks to my job as a game programmer, I come into contact with a lot of code for small mobile games. And it always amazes me how many game loop implementations are out there. You might wonder yourself how a simple thing like that can be written in different ways. Well, it can, and I will discuss the pros and cons of the most popular implementations, and give you the (in my opinion) best solution of implementing a game loop.

(Thanks to Kao Cardoso Félix this article is also available in Brazilian Portuguese, and thanks to Damian/MORT in Polish)

The Game Loop

Every game consists of a sequence of getting user input, updating the game state, handling AI, playing music and sound effects, and displaying the game. This sequence is handled through the game loop. Just like I said in the introduction, the game loop is the heartbeat of every game. In this article I will not go into details on any of the above mentioned tasks, but will concentrate on the game loop alone. That’s also why I simplified the tasks to only 2 functions: updating the game and displaying it. Here is some example code of the game loop in it’s most simplest form:

    bool game_is_running = true;

    while( game_is_running ) {
        update_game();
        display_game();
    }

The problem with this simple loop is that it doesn’t handle time, the game just runs. On slower hardware the game runs slower, and on faster hardware faster. Back in the old days when the speed of the hardware was known, this wasn’t a problem, but nowadays there are so many hardware platforms out there, that we have to implement some sort of time handling. There are many ways to do this, and I’ll discuss them in the following sections. First, let me explain 2 terms that are used throughout this article:

FPS
FPS is an abbreviation for Frames Per Second. In the context of the above implementation, it is the number of times display_game() is called per second.
Game Speed
Game Speed is the number of times the game state gets updated per second, or in other words, the number of times update_game() is called per second.

FPS dependent on Constant Game Speed

Implementation

An easy solution to the timing issue is to just let the game run on a steady 25 frames per second. The code then looks like this:

    const int FRAMES_PER_SECOND = 25;
    const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;

    DWORD next_game_tick = GetTickCount();
    // GetTickCount() returns the current number of milliseconds
    // that have elapsed since the system was started

    int sleep_time = 0;

    bool game_is_running = true;

    while( game_is_running ) {
        update_game();
        display_game();

        next_game_tick += SKIP_TICKS;
        sleep_time = next_game_tick - GetTickCount();
        if( sleep_time >= 0 ) {
            Sleep( sleep_time );
        }
        else {
            // Shit, we are running behind!
        }
    }

This is a solution with one huge benefit: it’s simple! Since you know that update_game() gets called 25 times per second, writing your game code is quite straight forward. For example, implementing a replay function in this kind of game loop is easy. If no random values are used in the game, you can just log the input changes of the user and replay them later. On your testing hardware you can adapt the FRAMES_PER_SECOND to an ideal value, but what will happen on faster or slower hardware? Well, let’s find out.

Slow hardware

If the hardware can handle the defined FPS, no problem. But the problems will start when the hardware can’t handle it. The game will run slower. In the worst case the game has some heavy chunks where the game will run really slow, and some chunks where it runs normal. The timing becomes variable which can make your game unplayable.

Fast hardware

The game will have no problems on fast hardware, but you are wasting so many precious clock cycles. Running a game on 25 or 30 FPS when it could easily do 300 FPS… shame on you! You will lose a lot of visual appeal with this, especially with fast moving objects. On the other hand, with mobile devices, this can be seen as a benefit. Not letting the game constantly run at it’s edge could save some battery time.

Conclusion

Making the FPS dependent on a constant game speed is a solution that is quickly implemented and keeps the game code simple. But there are some problems: Defining a high FPS will pose problems on slower hardware, and defining a low FPS will waste visual appeal on fast hardware.

Game Speed dependent on Variable FPS

Implementation

Another implementation of a game loop is to let it run as fast as possible, and let the FPS dictate the game speed. The game is updated with the time difference of the previous frame.

    DWORD prev_frame_tick;
    DWORD curr_frame_tick = GetTickCount();

    bool game_is_running = true;
    while( game_is_running ) {
        prev_frame_tick = curr_frame_tick;
        curr_frame_tick = GetTickCount();

        update_game( curr_frame_tick - prev_frame_tick );
        display_game();
    }

The game code becomes a bit more complicated because we now have to consider the time difference in the update_game() function. But still, it’s not that hard. At first sight this looks like the ideal solution to our problem. I have seen many smart programmers implement this kind of game loop. Some of them probably wished they would have read this article before they implemented their loop. I will show you in a minute that this loop can have serious problems on both slow and fast (yes, FAST!) hardware.

Slow Hardware

Slow hardware can sometimes cause certain delays at some points, where the game gets “heavy”. This can definitely occur with a 3D game, where at a certain time too many polygons get shown. This drop in frame rate will affect the input response time, and therefore also the player’s reaction time. The updating of the game will also feel the delay and the game state will be updated in big time-chunks. As a result the reaction time of the player, and also that of the AI, will slow down and can make a simple maneuver fail, or even impossible. For example, an obstacle that could be avoided with a normal FPS, can become impossible to avoid with a slow FPS. A more serious problem with slow hardware is that when using physics, your simulation can even explode!

Fast Hardware

You are probably wondering how the above game loop can go wrong on fast hardware. Unfortunately, it can, and to show you, let me first explain something about math on a computer. The memory space of a float or double value is limited, so some values cannot be represented. For example, 0.1 cannot be represented binary, and therefore is rounded when stored in a double. Let me show you using python:

>>> 0.1
0.10000000000000001

This itself is not dramatic, but the consequences are. Let’s say you have a race-car that has a speed of 0.001 units per millisecond. After 10 seconds your race-car will have traveled a distance of 10.0. If you split this calculation up like a game would do, you have the following function using frames per second as input:

>>> def get_distance( fps ):
...     skip_ticks = 1000 / fps
...     total_ticks = 0
...     distance = 0.0
...     speed_per_tick = 0.001
...     while total_ticks < 10000:
...             distance += speed_per_tick * skip_ticks
...             total_ticks += skip_ticks
...     return distance

Now we can calculate the distance at 40 frames per second:

>>> get_distance( 40 )
10.000000000000075

Wait a minute… this is not 10.0??? What happened? Well, because we split up the calculation in 400 additions, a rounding error got big. I wonder what will happen at 100 frames per second…

>>> get_distance( 100 )
9.9999999999998312

What??? The error is even bigger!! Well, because we have more additions at 100 fps, the rounding error has more chance to get big. So the game will differ when running at 40 or 100 frames per second:

>>> get_distance( 40 ) - get_distance( 100 )
2.4336088699783431e-13

You might think that this difference is too small to be seen in the game itself. But the real problem will start when you use this incorrect value to do some more calculations. This way a small error can become big, and fuck up your game at high frame rates. Chances of that happening? Big enough to consider it! I have seen a game that used this kind of game loop, and which indeed gave trouble at high frame rates. After the programmer found out that the problem was hiding in the core of the game, only a lot of code rewriting could fix it.

Conclusion

This kind of game loop may seem very good at first sight, but don’t be fooled. Both slow and fast hardware can cause serious problems for your game. And besides, the implementation of the game update function is harder than when you use a fixed frame rate, so why use it?

Constant Game Speed with Maximum FPS

Implementation

Our first solution, FPS dependent on Constant Game Speed, has a problem when running on slow hardware. Both the game speed and the framerate will drop in that case. A possible solution for this could be to keep updating the game at that rate, but reduce the rendering framerate. This can be done using following game loop:

    const int TICKS_PER_SECOND = 50;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 10;

    DWORD next_game_tick = GetTickCount();
    int loops;

    bool game_is_running = true;
    while( game_is_running ) {

        loops = 0;
        while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
            update_game();

            next_game_tick += SKIP_TICKS;
            loops++;
        }

        display_game();
    }

The game will be updated at a steady 50 times per second, and rendering is done as fast as possible. Remark that when rendering is done more than 50 times per second, some subsequent frames will be the same, so actual visual frames will be dispayed at a maximum of 50 frames per second. When running on slow hardware, the framerate can drop until the game update loop will reach MAX_FRAMESKIP. In practice this means that when our render FPS drops below 5 (= FRAMES_PER_SECOND / MAX_FRAMESKIP), the actual game will slow down.

Slow hardware

On slow hardware the frames per second will drop, but the game itself will hopefully run at the normal speed. If the hardware still can’t handle this, the game itself will run slower and the framerate will not be smooth at all.

Fast hardware

The game will have no problems on fast hardware, but like the first solution, you are wasting so many precious clock cycles that can be used for a higher framerate. Finding the balance between a fast update rate and being able to run on slow hardware is crucial.

Conclusion

Using a constant game speed with a maximum FPS is a solution that is easy to implement and keeps the game code simple. But there are still some problems: Defining a high FPS can still pose problems on slow hardware (but not as severe as the first solution), and defining a low FPS will waste visual appeal on fast hardware.

Constant Game Speed independent of Variable FPS

Implementation

Would it be possible to improve the above solution even further to run faster on slow hardware, and be visually more atractive on faster hardware? Well, lucky for us, this is possible. The game state itself doesn’t need to be updated 60 times per second. Player input, AI and the updating of the game state have enough with 25 frames per second. So let’s try to call the update_game() 25 times per second, no more, no less. The rendering, on the other hand, needs to be as fast as the hardware can handle. But a slow frame rate shouldn’t interfere with the updating of the game. The way to achieve this is by using the following game loop:

    const int TICKS_PER_SECOND = 25;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 5;

    DWORD next_game_tick = GetTickCount();
    int loops;
    float interpolation;

    bool game_is_running = true;
    while( game_is_running ) {

        loops = 0;
        while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
            update_game();

            next_game_tick += SKIP_TICKS;
            loops++;
        }

        interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
                        / float( SKIP_TICKS );
        display_game( interpolation );
    }

With this kind of game loop, the implementation of update_game() will stay easy. But unfortunately, the display_game() function gets more complex. You will have to implement a prediction function that takes the interpolation as argument. But don’t worry, this isn’t hard, it just takes a bit more work. I’ll explain below how this interpolation and prediction works, but first let me show you why it is needed.

The Need for Interpolation

The gamestate gets updated 25 times per second, so if you don’t use interpolation in your rendering, frames will also be displayed at this speed. Remark that 25 fps isn’t as slow as some people think, movies for example run at 24 frames per second. So 25 fps should be enough for a visually pleasing experience, but for fast moving objects, we can still see a improvement when doing more FPS. So what we can do is make fast movements more smooth in between the frames. And this is where interpolation and a prediction function can provide a solution.

Interpolation and Prediction

Like I said the game code runs on it’s own frames per second, so when you draw/render your frames, it is possible that it’s in between 2 gameticks. Let’s say you have just updated your gamestate for the 10Th time, and now you are going to render the scene. This render will be in between the 10Th and 11Th game update. So it is possible that the render is at about 10.3. The ‘interpolation’ value then holds 0.3. Take this example: I have a car that moves every game tick like this:

    position = position + speed;

If in the 10Th gametick the position is 500, and the speed is 100, then in the 11Th gametick the position will be 600. So where will you place your car when you render it? You could just take the position of the last gametick (in this case 500). But a better way is to predict where the car would be at exact 10.3, and this happens like this:

    view_position = position + (speed * interpolation)

The car will then be rendered at position 530. So basically the interpolation variable contains the value that is in between the previous gametick and the next one (previous = 0.0, next = 1.0). What you have to do then is make a “prediction” function where the car/camera/… would be placed at the render time. You can base this prediction function on the speed of the object, steering or rotation speed. It doesn’t need to be complicated because we only use it to smooth things out in between the frames. It is indeed possible that an object gets rendered into another object right before a collision gets detected. But like we have seen before, the game is updated 25 frames per second, and so when this happens, the error is only shown for a fraction of a second, hardly noticeable to the human eye.

Slow Hardware

In most cases, update_game() will take far less time than display_game(). In fact, we can assume that even on slow hardware the update_game() function can run 25 times per second. So our game will handle player input and update the game state without much trouble, even if the game will only display 15 frames per second.

Fast Hardware

On fast hardware, the game will still run at a constant pace of 25 times per second, but the updating of the screen will be way faster than this. The interpolation/prediction method will create the visual appeal that the game is actually running at a high frame rate. The good thing is that you kind of cheat with your FPS. Because you don’t update your game state every frame, only the visualization, your game will have a higher FPS than with the second method I described.

Conclusion

Making the game state independent of the FPS seems to be the best implementation for a game loop. However, you will have to implement a prediction function in display_game(), but this isn’t that hard to achieve.

Overall Conclusion

A game loop has more to it than you think. We’ve reviewed 4 possible implementations, and it seems that there is one of them which you should definitely avoid, and that’s the one where a variable FPS dictates the game speed. A constant frame rate can be a good and simple solution for mobile devices, but when you want to get everything the hardware has got, best use a game loop where the FPS is completely independent of the game speed, using a prediction function for high framerates. If you don’t want to bother with a prediction function, you can work with a maximum frame rate, but finding the right game update rate for both slow and fast hardware can be tricky.

Now go and start coding that fantastic game you are thinking of!

Koen Witters

Categories: Programming

131 Comments

Rafael · April 27, 2012 at 04:50

Hi there. First I want to say, that this is basically a very nice article! Everything I need is well explained, with additional infos, what can cause problems. So I tried the first implementation ‘FPS dependent on Constant Game Speed’ and observed, that my Nexus S will run every second time into the else case, where you comment that ‘SH** we’re running behind’. After looking at the Problem (implemented an FPSCounter without sleep) I see, that my FPS are 50+ as I realized, that even the best supercomputer will run in that ‘else case’ in this implementation – at least every second time. I think there is a problem with the sleepTime: If the Thread sleeps until the next tick, there is no additional time calculated to `updateGame’ and ‘displayGame’. So shouldn’t we calculate some time to update and display the Game and substract this time from the sleepTime?? Or did I just get something completly wrong?

Rodney Barbati · April 29, 2012 at 19:19

A basic rule of thumb – Don’t sleep threads in a game, ever. There is always something that your game or the operating system could be doing with those cycles.

And keep in mind that if you are sleeping a thread to wait for a given interval, then all the code you run at that interval is late. You want to be running your code (most likely position updates) during the time that you are attempting to sleep the thread, and render at the interval.

Also, sleeping the thread will prevent you from being able to add objects into your game that run at different rates.

William Warren · June 1, 2012 at 05:39

Wow this was amazing, been looking for this for ages.

Very informative post and helped me a lot to create a decent game loop for a little game I’m building.

Sean · June 12, 2012 at 06:00

This article is great, it really helped me to understand the options when it comes to a game loop. Thanks a lot!

Kenyan · July 20, 2012 at 10:02

Error! Garaff != Gaffer … s/Garaff/Gaffer @ChrisH

qner · July 28, 2012 at 03:12

Thank you! Very informative. Gonna try out right now.

Ian · August 7, 2012 at 16:27

Thank you for this article Koen.

BTW I wonder if there has been any new techniques introduced since 2009?

Hello · August 27, 2012 at 12:23

@Rodney Barbati

Correct me if I’m wrong, but if you sleep in a thread, your own thread sleeps, but the OS still uses cpu cycles, else it would mean that an application that sleeps hangs on the whole system.

Oleg · September 20, 2012 at 08:48

Nice article. Thank’s.

Sri Harsha Chilakapati · September 30, 2012 at 05:42

The interpolation is going greater than 4! And the obj is moving more. How could I fi it?

Christian Köhler · October 26, 2012 at 05:48

Hello,

the first alternative (let the FPS determine the game speed) is not as bad as you describe it. I have actually implemented this in several commercial games on different platforms.

The problems you describe are really there, but they are avoided easily:

– Fast machine: No problem, because I always made the game vsync limited. I know some CRTs were operated at 100 or 120Hz to avoid flicker. So I made sure the code works up to a limit of 250 FPS. There is no point in building a faster display system because it would be much faster than human vision. With the exception of benchmarking there is no reason to let a game run faster than vsync. But what if? If I detected less that a 250th sec, I just killed a single millisecond by sleeping until the delay was longer than 1/250s. Because of vsync this should never happen in reality.

-Slow machine: We decided there is no point in plying the game on a machine slower than about 10 FPS. For PC/Mac versions the system requirements make sure the game is faster than that most of the time. Of course there are some situations when the game is interrupted by something else even on a fast machine. For this reason I put an upper limit on the “Secsonds since last frame”. I usually set this to 0.2 secs (5 FPS). So the game will assume a time of 0.2s even if the notebook was in sleep mode for days between two frames. So gameplay will become slower in extreme situations, but there are no ill effects on physics or something.

Why no fixed physics ticks and variable speed rendering with interpolation?
I have evaluated this. For a console game I hat do consider PAL (25 FPS) and NTSC (30 FPS). If I set the physics step to a fixed 30 FPS, there are problems on PAL. Sometimes there would be two of these steps in one 25th second. In this game physics and collision detection where not trivial in terms of cpu time. Doing this twice between rendering two frames often took longer than the next sync resulting in a missed frame.
If I set the physics FPS to a fixed 25 on NTSC sometimes two frames are rendered without actual physics calculations. Of course there is still interpolation, but if your movements are non linear this may be “off” enough to be visible. The game won’t run as smooth as it could.
So the step time had to be variable anyway (at least 1/25 and 1/30). So why not use the actual time delay instead?

Christian

Magnus · October 28, 2012 at 10:45

Thanks a lot for this article, it really helped me out with my android game!
The interpolation for updating the display is a really smart thing that I probably wouldn’t have come up with myself 🙂

Henry · November 12, 2012 at 15:19

Just wanted to give sincere, sincere thanks for this article. It helped me out a lot (and I’m not even programming a game loop, just an fps-setter), and is a phenomenal resource for this important coding construct.

Keep it up!

David · November 19, 2012 at 13:10

Thank you so very much for that succinct explanation of interpolation. Nothing else I have read even comes close. I have dug through articles on game loop timings trying to find one that could explain how to utilize this concept. Most of these articles went something like this, “Of course you could use interpolation.”, “Just interpolate the steps. (Like that helps)” or worse yet, “Here is a link to the linear interpolation article on wikipedia.” Thanks for explaining it in a way that is actually useful for game development.

Rick · December 11, 2012 at 09:25

In the second to last method you say for fast PC’s “The game will have no problems on fast hardware, but like the first solution, you are wasting so many precious clock cycles that can be used for a higher framerate.”. Yet this is also true for the last method, which you hint to being the best but don’t mention this “waste”. Isn’t it also meaningless, given the fast PC will only ever run the logic 25 cycles a second. The idea with the fast PC is that it’s basically chilling, waiting for something to do most of the times anyway because it’s meeting it’s 25 cycles per second logic rate with ease. Just want to be sure I’m reading that correctly.

Kerim · February 13, 2013 at 00:00

Thank you. Very clear explanation of different approaches! I have a few questions though if you please.
If your `interpolation` code calculates position `view_position = position + (speed * interpolation)`, than what’s your `update_game` doing? How is its position calculation is different from prediction’s? Can I guess that it’s collision detection, more complex(beyond just pos+=speed) physics calculation and something else? The doesn’t it result in a problem when new calculated in `update_game` position value differs quite a bit from the one interpolated?

Zippy · February 23, 2013 at 19:10

Awesome article – I’m implementing the last method (With interpolattion) in my Android app and it really does smooth out the movement of the sprites. Just one question though, as I’m working on a mobile device I don’t want the rendering to run flat-out/as fast as possible (because of the potential to affect battery life) – could someone please advise the best way to limit the rendering? At the moment all I’ve done is set a Boolean flag to true in my game update method and to false in my draw method, then in my draw method I check that flag. If it’s true, I draw, if not I don’t. So this means that the rendering only occurs at the same rate as the game updates which is great, but it seems to cause a slight ‘jerkiness’ in the sprite movement – any help would be appreciated!

Daniel · April 5, 2013 at 02:44

Nice post! Thanks!

kiwee · May 12, 2013 at 18:39

Rodney Barbati :
A basic rule of thumb – Don’t sleep threads in a game, ever. There is always something that your game or the operating system could be doing with those cycles.
And keep in mind that if you are sleeping a thread to wait for a given interval, then all the code you run at that interval is late. You want to be running your code (most likely position updates) during the time that you are attempting to sleep the thread, and render at the interval.
Also, sleeping the thread will prevent you from being able to add objects into your game that run at different rates.

what???
If you don’t sleep, the cpu usage goes up to 100% though

Mahan · August 6, 2013 at 05:11

This is what I was looking for, for past couple of weeks! I mean really there is no specific article based on such important problem as you’ve mentioned earlier. Thank you and keep going with your job!

Mahan · August 6, 2013 at 10:58

I’ve got a question for you. I don’t know if this is related to me or it’s a global thing. I’ve used last implementation that you’ve provided, but it raises my CPU usage to 100%. I think render is using all of my system capacities and that’s good, but it’s not good when it keeps my CPU at the maximum rate of working during runtime. Is this a normal behavior and what would you suggest?

gabriel · August 12, 2013 at 09:54

brilliant article

Martin · October 3, 2013 at 04:11

@Mahan
You could try restricting your renderings to a max fps. Send your game to sleep if it has nothing to do instead of drawing dozens of frames 🙂

updates_per_second = 25
update_intervall = 1000/25

max_fps = 50
redraw_intervall = 1000/50

max_frameskip = 5

game_is_running = True
t_next_update = getTime()
t_next_redraw = getTime()

while (game_is_running):
loops = 0
while ( getTime() > t_next_update & loops t_next_redraw): # draw
interpolation = (getTime() + update_intervall – t_next_update) /
update_intervall
# if we are behind by more than one update intervall only draw
# how it would look like after the next update:
interpolation = min(interpolation, 1)
display_game(interpolation)
# set the next redraw to a future point in time
# (we might have fallen behind on slow machines):
while (t_next_redraw < getTime()):
t_next_redraw += redraw_intervall
# if currently nothing to do:
if (getTime() < t_next_redraw and getTime() < t_next_update):
# sleep until the next update or redraw time, whatever comes first
sleep(min(t_next_redraw, t_next_update) – getTime())

Jitech · November 25, 2013 at 21:25

I do this :

int currentTime = getCurrentTime();
int previousTime = currentTime;
int tick = 40; //minimum 25 game updates per second (1000/40)

while(1)
{
int elapsedTime = currentTime – previousTime;

while(elapsedTime > 0) {
UpdateGame(currentTime – previousTime);
elapsedTime -= tick;
previousTime = currentTime;
currentTime = getCurrentTime();
}

DisplayGame();
currentTime = getCurrentTime();
}

UpdateGame range : min = 25/s, max = infinite
Max FPS = infinite

Jitech · November 25, 2013 at 21:40

*UpdateGame range : min = 25/s, max = 1000/s

Jitech · November 25, 2013 at 21:51

But to have exactly 25 update/s substitute while(elapsedTime > 0) by while(elapsedTime > tick).

mar.k · December 12, 2013 at 10:52

I just wondered, doesn’t the following line

view_position = position + (speed * interpolation)

have to be:

view_position = position + speed + (speed * interpolation)

Radu · December 13, 2013 at 06:25

@mar.k
Don’t see how… position should already be “position += speed” from the previous tick.

Anna · December 30, 2013 at 13:38

Thanks, that helped a lot!

ZeebraZeck · January 9, 2014 at 08:11

I use strategy design pattern to determine which algorithm i should use when to calculate the FPS.
First i measure the FPS in the computer i run my game on, and it does some test of the game without any restriction in fps, and then i determine which FPS algorithm it should use. With this way i could find the best benefit for the game for just that computer. The tests could been done when intro begins before actually gaming starts.

Thanks for the article.

Caio Sica · January 17, 2014 at 14:35

I’d like to thank you, your article was very enlightening.
ZeebraZe and Martin comments also added great information and perspective for those that are learning.

gamedude_7 · February 15, 2014 at 11:27

shouldn’t it be while( GetTicks() < next_game_tick && loops < MAX_FRAMESKIP ) ?

Adrien Luxey · February 23, 2014 at 15:11

Dude, you rock.

I am making a program about AI with neural networks and genetic algorithms. As neural networks take a lot of time to become intelligent, I needed to be able to increase the update loop’s speed (your TICKS_PER_SECOND) without bothering with the display.
This is way better than everything I had come up with, thanks !

Pap · April 15, 2014 at 15:41

This article is not really helpful. I’ll try to ignore the haughty style (e.g., “the one and only article that gives the game loop the attention it deserves” – nonsense by the way, there are plenty of them, and actually better than this one).
The article doesn’t even mention vsync. I would suggest the author to have a look at terms like “vsync”, “adaptive vsync”, and functions like GLEW’s “glXSwapIntervalSGI()”, “glXSwapIntervalMESA()” for Linux, or “wglSwapIntervalEXT()” for Windows. Until then, I suggest the readers of this page to look elsewhere for an article with less blatant haughty and more helpful information.

Christian Köhler :
Hello,
the first alternative (let the FPS determine the game speed) is not as bad as you describe it. I have actually implemented this in several commercial games on different platforms.

    rab · September 18, 2015 at 09:23

    Pap.. it’s a ward we use to describe useless information.. quite an appropriate name really.. my view is this article really opens up the possibilities for those who are new to these concepts, you’re comment really exposes the inner frailties you possess, try to be more magnanimous, it’s no skin off your nose.. i notice you don’t give any alternatives just criticism..

    brilliant article and deserves a medal
    rab

      rab · September 18, 2015 at 09:24

      word

Zbiggy · April 25, 2014 at 16:54

“…you are wasting so many precious clock cycles. Running a game on 25 or 30 FPS when it could easily do 300 FPS… shame on you! You will lose a lot of visual appeal with this, especially with fast moving objects.”

No, you won’t – since you won’t see any (significant) difference, when you reached 60 FPS. So why you would want to do 300 FPS – even, if it’s easy? Exactly this would be a clock cycles waste! There’s no need to worry about the cycles not used by the game for superfluous FPS-es (I mean the ones above 60 FPS); your multitasking OS will take care of them, releasing CPU power to other running programs.

Slippy · June 7, 2014 at 11:26

Anybody knows how i could implement the last game loop in java?

I tried replacing the GetTickCount() with System.currentTimeMillis()
yet it doesnt work correctly.

Slippy · June 7, 2014 at 11:29

@Marku S
Hey could you post your basic game loop code here. Im trying to implement the same loop in java but i cannot get it to work.

b5cully · June 26, 2014 at 08:42

@Slippy
// GetTickCount()/tickcount returns the current number of milliseconds
/ that have elapsed since the system was started

I think this is a very important bit here to answer your question. The number returned by System.currentTimeMillis() is way to large in order to work with this algorhitm (if I’m not mistaken it returns a whole date in milliseconds, so it loosk like it creates such a huge delay you’re not even noticing any changes).

The code I have looks like this: http://pastebin.com/5kx0CFBm
It’s just simulating the loop but judging by console output, it works fine. You may need to adapt to the tickcounter variable your own environment though.

reader · July 10, 2014 at 17:49

Umm….
http://www.mysecretroom.com/www/programming-and-software/android-game-loops

this is exactly your post…??

Koen Witters · July 11, 2014 at 00:51

@reader
Yes indeed! I contacted the author to be so kind and reference my original article. Thanks for noticing this and letting me know! Much appreciated!

Ixnatifual · September 17, 2014 at 11:47

@Slippy Try using System.nanoTime() instead. It’s more precise.

James · September 21, 2014 at 04:41

You sir, are a genious! I think this is what’s missing in my game where the frame rate occassionaly stutters when the UPS drops. Thank you!

Sam · September 23, 2014 at 12:32

I am struggling to see why he is calculating the interpolation this way:

interpolation = float( GetTickCount() + SKIP_TICKS – next_game_tick )
/ float( SKIP_TICKS );

and not this way:

interpolation = float( next_game_tick – GetTickCount())
/ float( SKIP_TICKS );

To me the second approach seems much more intuitive to understand. Is it both the same or did I miss something?

Sam · September 23, 2014 at 12:33

@Sam
Just saw that I posted my question as a reply. Can someone fix this? Thank you

Jordan · November 1, 2014 at 09:09

This is a fantastic article, and has helped me a great deal! Thank you very much for posting this.

Dudeson · November 17, 2014 at 19:13

@Kerim
Prediction is bullshit. Use regular interpolation instead. I have no Idea why this guy here advocates prediction. It will cause jerky object movements and stuff.

Winston · November 30, 2014 at 12:16

This article really helped me to implement a game speed in my game.
Now I change my game speed and limit my FPS on the fly in the game.
All movements, rotations and special effects are smooth and have always the same speed which is what we want in 3D games.
The article says 2 things:
1. Use a fixed time step for the game
2. Interpolate results for rendering
If you do this, it’ll work.

THIS IS INDEED ONE OF THE FEW ARTICLES THAT ONE CAN TRUST!
Koon solo… vree veel bedankt!

asmith2306 · April 13, 2015 at 02:09

Hi,

what is supposed to be in the getTickCount function above?

Thanks

Emin · April 13, 2015 at 04:21

You can make this more generic and ufesul by using the constructor and destructor methods (see also the RAII). Scoping then allows you to time functions with a varying number of parameters or more complicated constructs. E.g., struct ExecutionTimer{ ExecutionTimer(long & result) : result_(result) { result_ = GetTickCount(); } ~ExecutionTimer() { result_ += GetTickCount(); } long & result_;};int main(){ long timer = 0; { ExecutionTimer et(timer); doSleep(); } std::cout << Code executed in << timer << ms \n ;}

Anne-Katrine · May 19, 2015 at 09:03

@asmith2306

asmith230 in java/android you have the SystemClock.uptimeMillis() to use. In C/C++ I think there actually is GetTickCount function – if not then there is one that can do the same thing.

Leave a Reply to Jitech Cancel reply

Your email address will not be published. Required fields are marked *