Keyboard State and Key States

Last updated on February 9th, 2019

In the next chapter we will see how so called events are processed to handle input of any kind (keyboard, mouse, joystick,…) Before that I’d like to introduce a simple, yet powerful way to handle keyboard input.

The keyboard state represents the state (pressed = 1 or unpressed = 0) of all the keyboard keys, hence the key states. By

we have easy access to this array.

Keyboard state demo.
The red rectangle can be moved by the WASD keys by reading out their key states.

The following code example will draw a red rectangle which can be moved by the WASD keys. Therefore we read out their key states on every cycle of the program loop.

To get the keyboard state, we define a unsigned 8 bit pointer variable sdlKeyboardState in the var clause. It points to the array of key states.

After setting up a SDL2 window and and preparing a SDL2 rectangle, the program loop is entered. Here we need to update the event queue by procedure SDL_PumpEvents. After that we can grab the keyboard state by the former mentioned function SDL_GetKeyboardState. The argument should be nil. These actions have to performed on every cycle.

We now can check for the of any key in the array by sdlKeyboardState[SDL_SCANCODE_…] using its
scancode as a handle (e.g. SDL_SCANCODE_ESCAPE for the escape key) and react as desired, e.g. exit the program loop or change the x/y coordinates of the rectangle. The scancode represents the position of the related key state in the array. A detailed description of scancodes in the next chapter. A list of all the scancodes shows all possible scancodes.

← previous Chapter | next Chapter →

Leave a Reply