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
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