Polling is particularly useful for handling continuous interactions where the state of input devices needs to be checked regularly. Here are some common examples of such interactions:
In many games, character movement is controlled by holding down keys. Polling is ideal for this because you need to continuously check the state of movement keys (e.g., W, A, S, D) to determine the character's movement direction.
#include <SDL.h>
#include <iostream>
class Window {
public:
Window() {
SDL_Init(SDL_INIT_VIDEO);
SDLWindow = SDL_CreateWindow(
"Continuous Movement",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_SHOWN
);
}
~Window() {
SDL_DestroyWindow(SDLWindow);
SDL_Quit();
}
void HandleMovement() {
const Uint8* state = SDL_GetKeyboardState(NULL);
if (state[SDL_SCANCODE_W]) {
std::cout << "Moving Up\n";
}
if (state[SDL_SCANCODE_A]) {
std::cout << "Moving Left\n";
}
if (state[SDL_SCANCODE_S]) {
std::cout << "Moving Down\n";
}
if (state[SDL_SCANCODE_D]) {
std::cout << "Moving Right\n";
}
}
private:
SDL_Window* SDLWindow{nullptr};
};
int main(int argc, char* argv[]) {
Window GameWindow;
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
GameWindow.HandleMovement();
// Rendering code here
}
return 0;
}
Moving Up
Moving Left
In 3D applications, camera control is often handled by polling the mouse and keyboard inputs to adjust the camera position and orientation continuously.
#include <SDL.h>
#include <iostream>
class Window {
public:
Window() {
SDL_Init(SDL_INIT_VIDEO);
SDLWindow = SDL_CreateWindow(
"Camera Control",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_SHOWN
);
}
~Window() {
SDL_DestroyWindow(SDLWindow);
SDL_Quit();
}
void HandleCamera() {
int x, y;
SDL_GetMouseState(&x, &y);
std::cout << "Mouse Position: ("
<< x << ", " << y << ")\n";
}
private:
SDL_Window* SDLWindow{nullptr};
};
int main(int argc, char* argv[]) {
Window GameWindow;
bool running = true;
SDL_Event event;
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
}
GameWindow.HandleCamera();
// Rendering code here
}
return 0;
}
Mouse Position: (320, 240)
In RTS games, unit selection and map scrolling are often handled continuously. Polling helps to keep track of the mouse and keyboard state to update selections and scroll the map smoothly.
Polling is well-suited for continuous interactions where the input state needs to be checked regularly.
It provides a straightforward way to handle real-time updates, ensuring that your application can respond immediately to user inputs. Examples include character movement, camera control, and interactions in RTSÂ games.
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.