Game Loop: Difference between revisions

From C# Gamedev Wiki
No edit summary
No edit summary
Line 14: Line 14:
In practice game loops may have a lot more code.  They may wait a certain amount of time between passes, do less processing on certain passes than others, contain exit logic, etc.
In practice game loops may have a lot more code.  They may wait a certain amount of time between passes, do less processing on certain passes than others, contain exit logic, etc.


There are two main types of game loops:
==Simple Update and Draw==
In the simple example above, the game updates and draws at the same rate. 
 
<syntaxhighlight lang="cs">
void GameLoop()
{
    while (true)
    {
        Update();
        Draw();
    }
}
</syntaxhighlight>
 
This was a common way to design video games when they were first made, and came with the following pros and cons:
 
*Pros
**Even when the game slows, down physics and game logic are still processed in a consistent manner.
*Cons
**If either the <code>Update()</code> or the <code>Draw()</code> took too much time, the game would slow down.
**Game may not run at full speed on weaker hardware.
 
 
 
==Timesteps==
There are two main types of game loops timesteps:
*[[Fixed Step]] - the loop processes equal intervals of game time
*[[Fixed Step]] - the loop processes equal intervals of game time
*[[Variable Step]] - the loop processes varying intervals of game time
*[[Variable Step]] - the loop processes varying intervals of game time


[[Category:Basics]]
[[Category:Basics]]

Revision as of 14:10, 9 June 2024

A game loop is a continuous loop that runs an Update() method and a Draw() method. Below is the simplest example of a game loop:

void GameLoop()
{
    while (true)
    {
        Update();
        Draw();
    }
}

In practice game loops may have a lot more code. They may wait a certain amount of time between passes, do less processing on certain passes than others, contain exit logic, etc.

Simple Update and Draw

In the simple example above, the game updates and draws at the same rate.

void GameLoop()
{
    while (true)
    {
        Update();
        Draw();
    }
}

This was a common way to design video games when they were first made, and came with the following pros and cons:

  • Pros
    • Even when the game slows, down physics and game logic are still processed in a consistent manner.
  • Cons
    • If either the Update() or the Draw() took too much time, the game would slow down.
    • Game may not run at full speed on weaker hardware.


Timesteps

There are two main types of game loops timesteps:

  • Fixed Step - the loop processes equal intervals of game time
  • Variable Step - the loop processes varying intervals of game time