Events, keyboard & mouseSDL 3.2

SDL_GetKeyboardState

Returns SDL's array of key states: `keys[SDL_SCANCODE_W]` is true while W is held.

Signature

const bool * SDL_GetKeyboardState(int *numkeys);

How it works

Events tell you when a key goes down; this array tells you whether it IS down. That is what continuous movement needs: move while held, in every frame.

The array is indexed by scancode, the physical position of the key. SDL_SCANCODE_W is the key where W sits on a US keyboard, so WASD stays in the same place on AZERTY. In SDL3 the entries are bool (they were Uint8 in SDL2).

Parameters

numkeysint *

Where to write the array length, or NULL.

Return value

A pointer owned by SDL, valid for the whole program. Get it once; its contents update during event processing.

Example

example.cpp
1const bool* keys = SDL_GetKeyboardState(nullptr);
2// every frame, after the event loop:
3float dx = keys[SDL_SCANCODE_D] - keys[SDL_SCANCODE_A];
4float dy = keys[SDL_SCANCODE_S] - keys[SDL_SCANCODE_W];
5player.x += dx * speed * dt;
6player.y += dy * speed * dt;
Official SDL wiki