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:
SDL_PollEvent
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.
Answers to questions are automatically generated and may not have been reviewed.
A step-by-step guide on setting up SDL2 and useful extensions in a project that uses CMake as its build system