When programming a game you’ll notice there is a main loop that handles: input, physics/gameworld, and output – this is the game loop.
What is a Game Loop?
A game loop is a fundamental structure used in most video games to control the flow of the game. It is essentially an infinite loop that repeatedly updates the game state.
- Input: The game loop starts by checking for and collecting any input. This could be from the player, such as keyboard or mouse actions, or incoming data. This input is then processed and used to update the game state.
- Update: The game state is updated based on the received input and the current state of the game. This includes updating the positions of game objects, checking for collisions, applying game rules, and managing any necessary calculations for physics.
- Render: After the game state has been updated, the graphics engine renders the game world and all its objects based on the new state. This involves drawing the background, characters, objects, and other visual elements onto the screen.
- Display: The rendered frame is displayed on the screen, allowing the player to see the updated game state. This step is usually synchronized with the monitor’s refresh rate to maintain a smooth and consistent visual experience.
- Loop: The process then returns to the beginning, where the loop continues indefinitely, continuously updating, rendering, and displaying the game state as long as the game is running.
Below is a simple game loop written in C++.
int main() {
// Delta time
float dt{ 0.0f };
bool isGameRunning{ true };
// Game loop
while (isGameRunning) {
// Handle input
// networking
// user controls
// Handle game world
// calculate physics
// update game state
// Handle output
// rendering
}
// Handle clean up
return 0;
}