Implementing a Basic Game Loop with SDL2
The lesson's example code uses a simple while loop for the main game loop. What does a more complete game loop look like in SDL2?
A typical game loop in SDL2 consists of three main parts: handling events, updating the game state, and rendering the game.
Here's a basic structure:
#include <SDL.h>
const int FPS = 60;
const int DELAY_TIME = 1000.0f / FPS;
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window{SDL_CreateWindow(
"Game Loop Example",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600, SDL_WINDOW_SHOWN
)};
SDL_Renderer* renderer{SDL_CreateRenderer(
window, -1, 0)};
Uint32 frameStart, frameTime;
bool quit{false};
while (!quit) {
frameStart = SDL_GetTicks();
// 1. Handle events
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = true;
}
}
// 2. Update game state
// ...
// 3. Render
SDL_SetRenderDrawColor(
renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// Render game objects
// ...
SDL_RenderPresent(renderer);
frameTime = SDL_GetTicks() - frameStart;
if (frameTime < DELAY_TIME) {
SDL_Delay((int)(DELAY_TIME - frameTime));
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
This game loop:
- Handles events (such as user input) with
SDL_PollEvent
- Updates the game state (e.g., positions of game objects) based on the events and game logic
- Renders the current game state using the SDL rendering functions
Additionally, it measures the time taken by each frame using SDL_GetTicks()
, and if the frame time is less than the desired delay time (1000 / FPS), it delays the loop using SDL_Delay()
to maintain a consistent frame rate.
This prevents the game from running too fast on high-performance machines and helps to decouple the game logic from the rendering speed.
Of course, this is just a basic structure, and real-world game loops can be much more complex, incorporating fixed time steps, interpolation, and other advanced techniques for smoother gameplay.
Building SDL2 from a Subdirectory (CMake)
A step-by-step guide on setting up SDL2 and useful extensions in a project that uses CMake as its build system