SDL timers are a useful tool to perform actions at set intervals, independent of your main game loop. Here’s a simple way to set up a timer that triggers every second:
#include <SDL.h>
#include <iostream>
Uint32 my_callback(Uint32 interval, void* param) {
std::cout << "Timer callback triggered!\n";
// Return the interval to reset the timer
return interval;
}
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_TIMER);
SDL_TimerID my_timer_id = SDL_AddTimer(
1000, my_callback, NULL);
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) running = false;
}
}
SDL_RemoveTimer(my_timer_id);
SDL_Quit();
return 0;
}
Timer callback triggered!
Timer callback triggered!
Timer callback triggered!
This timer will call my_callback()
every 1000 milliseconds (1 second), and it will print a message to the console each time it is triggered.
Answers to questions are automatically generated and may not have been reviewed.
Step-by-step guide on creating the SDL2 application and event loops for interactive games