š¾ Teaching the Game Loop
A Teaching Tip for CodeHS Game Design Courses
Most games have a defined structure or architecture for the overall game program. The game program can be divided into three main parts:
- Initialization (Init or Start)
- Game Loop (Main or Update)
- Termination (Cleanup or Quit)
There are some functions and setup blocks of code that may exist in a game program outside of these three main functions. However, most game programs begin with this basic structure. The graphic shows how these three main components work together to create the flow of a game program. As you can see, the game loop or main update is where the bulk of the code lies.
Game loops are crucial to updating player input, movement of game objects including AI actions, and updating the game rendering or visuals on the screen. Within the game loop code, students may find collision systems, physics engines, and event handlers.
Sometimes game engines omit one or more of these three game program functions or use alternative terms to describe them, such as start instead of init or update instead of loop. Hereās an example of the C# script template thatās used with scripts created in the Unity game engine. Notice that two of the structural components are presentāāāthe initialization with void Start( ) and game loop with void Update( ).
The game loop or update is typically called once per frame in Unity. Sometimes the game loop commands and functions are called based on delta time or a specified elapsed time. For example, in the CodeHS Project: Breakout from the Introduction to JavaScript curriculum, an update function or game loop could be called on with a setTimer(update, 30) statement in the start function. This would run the game loop every 30 milliseconds. Take a look at these two functions from a Project: Breakout program.
ā Teaching Tip ā
You can use code examples like these (shown above) to help students identify the three primary game program structures that are often required to develop a video game.
- Ask students to think about what types of gameplay systems might be found in the codeās game loop.
- Can they locate clues in the code for a physics system (any variables for gravity, speed, or acceleration)?
- Can they locate any code that might be part of a collision resolution that controls what happens when an enemy is destroyed?
Learn more about the CodeHS Game Design in Unity Courses here:
Questions? Contact the CodeHS Team at hello@codehs.com today.