Generally, what are the core things that one should do in the game loop, and what are some things that one shouldn't do in the game loop?
Asked
Active
Viewed 9.9k times
137
-
Note to future visitors: although this was an interesting and relevant question when it was asked ~10 years ago when the site was shiny and new, this is not a good representation of the questions we expect today; it is on-topic but does not really present an issue to be solved. – Vaillancourt Jan 04 '21 at 20:44
1 Answers
136
The main game loop handles three major tasks:
- Get user input
- Update the game state
- Draw the game
A simple game loop just mushes these three tasks into one while loop. This has some undesired results:
- Game runs at different speeds on different computers.
- CPU (can be needlessly) pegged at 100% usage.
- "Game states"/menus are missing or mixed with game code.
- Main game loop is very long and hard to maintain.
- Code is difficult to extend/port to other platforms.
Advanced gamed loops address the issues listed above. Here are some useful articles:
- deWiTTERS Game Loop
- Integrating a timer into a game loop
- Managing Game States in C++
- XNA Game State Management and Network Game State Management
- Understanding the Game Main Loop
For an excellent example game loop, take a look at the Allegro skater demo game:
- Game loop code is in framework.c.
- Browse full source code here.
Other related resources:
- Glenn Fiedler's article about robust framerate independence, "Fix Your Timestep!"
- This deals with a number of different ways to write your game loop: Multithreaded Game Engine Architectures
- Game Loop · Sequencing Patterns · Game Programming Patterns
Game loops often do the same type of work for most games, so I have been thinking of a way to make a generalized game framework. It is better to write one implementation of a game loop and share it between games. It saves work when creating a new game, and improvements to the shared game loop can be shared by all games (for example, adding a FPS counter or screen capture feature).