Efficient Handling of Key Presses in SDL2
How can I efficiently handle multiple key presses in SDL2?
Handling multiple key presses efficiently involves using SDL_GetKeyboardState()
which provides the current state of the keyboard. It's more efficient than handling individual key press events because it allows you to check the state of all keys at once in your game loop:
#include <SDL.h>
#include <iostream>
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window =
SDL_CreateWindow(
"Key Press Example", 100, 100, 640, 480, 0);
const Uint8* state = SDL_GetKeyboardState(NULL);
bool running = true;
SDL_Event event;
while (running) {
SDL_PollEvent(&event);
if (event.type == SDL_QUIT) running = false;
if (state[SDL_SCANCODE_UP])
std::cout << "Up key is pressed.\n";
if (state[SDL_SCANCODE_DOWN])
std::cout << "Down key is pressed.\n";
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Down key is pressed.
Down key is pressed.
Down key is pressed.
Up key is pressed
Implementing an Application Loop
Step-by-step guide on creating the SDL2 application and event loops for interactive games