Using timer and game loop

You normally don’t use conventional timers in games. Games have a very different mechanism for handling their logic and the time that passed, they normally don’t work with timers or not in the way you would expect:

Games normally have something called a game loop. Generally speaking it’s three main functions that are called one after the other in a loop:

while(running)
{
    HandleUserInput();
    ChangeWorld();
    Render();
}

You get user input, you change the game world accordingly and you draw it to the screen. Now, the faster your computer is, the faster this loop runs. That’s good for the graphics (think FPS), but bad for the game. Imagine Tetris where every frame the blocks move. Now I would not want to buy a faster computer, the game would get more difficult that way.

So to keep the game speed constant independent of the power of the computer, the loop considers the time passed:

while(running)
{
    var timePassedSinceLastLoop = CalculateTimeDelta();

    HandleUserInput();
    ChangeWorld(timePassedSinceLastLoop);
    Render();
}

Now imagine a cooldown for something in game. The player pressed “a”, some cool action happened and although he may press “a” again, nothing will happen for the next 5 seconds. But the game still runs and does all the other things that may happen ingame. This is not a conventional timer. It’s a variable, lets call it ActionCooldown, and once the player triggers the action, it’s set to 5 seconds. Every time the world changes, the timePassed is subtracted from that number until it’s zero. All the time, the game is running and handling input and rendering. But only once ActionCooldown hits zero, another press of “a” will trigger that action again.

The ChangeWorld method includes all automatic changes to the world. Enemies, missiles, whatever moves without player interaction. And It moves based on time. If the enemy moves one square per second, You need to make his coordinate a float and add a fraction of a square every time the loop is run.

Lets say you have 30 fps so your loop runs 30 times a second. Your enemy now needs to move 1/30 of a square each loop. Then it will in the end have moved one full square per second.

Leave a Comment