SDL_PollEvent()
and SDL_PumpEvents()
are both used to handle events in SDL, but they serve different purposes and work in different ways.
SDL_PollEvent()
SDL_PollEvent()
is used to fetch events from the event queue. Each call to SDL_PollEvent()
retrieves the next event in the queue and removes it from the queue. This function is typically called in a loop to process all available events. Here’s an example:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow(
"Event Polling",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_SHOWN
);
SDL_Event event;
bool running = true;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
// Rendering code here
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
SDL_PumpEvents()
SDL_PumpEvents()
updates the event queue by processing the pending input events. It does not remove or fetch events from the queue.
Instead, it prepares the event queue to be read by functions like SDL_PollEvent()
. It’s useful when you want to ensure the event queue is updated without fetching the events immediately.
Here’s how you might use it:
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow(
"Event Pumping",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_SHOWN
);
bool running = true;
while (running) {
SDL_PumpEvents();
// Now the event queue is updated
// You can check the state of the keys, for example:
const Uint8* state = SDL_GetKeyboardState(NULL);
if (state[SDL_SCANCODE_ESCAPE]) {
running = false;
}
// Rendering code here
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
SDL_PollEvent()
retrieves and removes events from the queue, while SDL_PumpEvents()
only updates the queue without removing any events.SDL_PollEvent()
when you need to handle specific events. Use SDL_PumpEvents()
when you need to update the event queue for functions that depend on the current event state, such as SDL_GetKeyboardState()
.By understanding these differences, you can choose the appropriate function based on your needs for event handling in SDL.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to detect and handle keyboard input in SDL2 using both event-driven and polling methods. This lesson covers obtaining and interpreting the keyboard state array.