Creating the Main Loop with SDL2

Efficient Handling of Key Presses in SDL2

How can I efficiently handle multiple key presses in SDL2?

Abstract art representing computer programming

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.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 27 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved