In previous lessons, we introduced how we can detect and react to keyboard input through the event loop:
#include <SDL.h>
void HandleKeyboardEvent(SDL_KeyboardEvent& E) {
// ...
}
int main(int argc, char** argv) {
Window GameWindow;
SDL_Event Event;
while (true) {
while (SDL_PollEvent(&Event)) {
if (Event.type == SDL_KEYDOWN)
HandleKeyboardEvent(Event.key);
}
}
SDL_Quit();
return 0;
}
However, there is another option. At any time within our application, we can query SDL to find out which keys are currently pressed.
SDL maintains an array of UInt8
values to represent the state of the user’s keyboard. This array has an integer for every key on the user’s keyboard, and we can receive a const
pointer to it using the SDL_GetKeyboardState()
function.
This function receives a pointer to an integer as an argument, which it updates with the size of the array:
#include <iostream>
#include <SDL.h>
class Window {/*...*/}
void HandleKeyboard() {
int Size;
SDL_GetKeyboardState(&Size);
std::cout << "Array Size: " << Size;
}
int main(int argc, char** argv) {
Window GameWindow;
SDL_Event Event;
HandleKeyboard();
while (true) {/*...*/}
SDL_Quit();
return 0;
}
Array Size: 512
Note that the array’s size will typically be larger than the number of keys on our keyboard, meaning not every position is assigned to a key. The main reason the size is provided is to communicate the upper bound of the array, which we may need to know if we were iterating through it, for example.
If we don’t need to know the size, we can pass a nullptr
:
void HandleKeyboard() {
SDL_GetKeyboardState(nullptr);
}
The array returned by SDL_GeyKeyboardState()
is an example of a C-style array. These are much more primitive than standard library containers such as a std::vector
.
A C-style array is simply a pointer to the first element in the collection. Given this array is a collection of UInt8
objects in this case, the type of the array is therefore a UInt8*
- a pointer to a UInt8
.
This array is managed internally by SDL and not something we should change, so it is additionally marked as const
:
void HandleKeyboard() {
const Uint8* State {
SDL_GetKeyboardState(nullptr)};
}
C-style arrays are so primitive they don’t even keep track of their own size. That needs to be communicated separately. In the case of SDL_GetKeyboardState()
, this is done by updating a variable we provide a pointer to.
We cover C-style arrays in more detail here:
Once we acquire the array returned by SDL_GetKeyboardState()
, we can store it in a variable and reuse it as needed.
The array is kept updated at all times by SDL, so we don’t need to call the SDL_GetKeyboardState()
function repeatedly to get the latest state.
Once we have the keyboard array from SDL_GetKeyboardState()
, we can determine if a key is currently held down by investigating the corresponding entry within that array. The index we need for each key is the scan code of that key, which SDL provides variables for.
For example, to determine if the spacebar is currently held down, we would check the index represented by SDL_SCANCODE_SPACE
:
void HandleKeyboard() {
const Uint8* State {
SDL_GetKeyboardState(nullptr)};
State[SDL_SCANCODE_SPACE];
}
The Uint8
value at each array position is 1
if the corresponding key is pressed, and 0
otherwise. 1
is truthy, and 0
is falsy, so we can directly use these values as booleans.
Below, we check on every frame whether the spacebar is held or not:
#include <iostream>
#include <SDL.h>
class Window {/*...*/}
void HandleKeyboard() {
const Uint8* State {
SDL_GetKeyboardState(nullptr)};
if (State[SDL_SCANCODE_SPACE]) {
std::cout << "Space is held\n";
} else {
std::cout << "Space is not held\n";
}
}
int main(int argc, char** argv) {
Window GameWindow;
SDL_Event Event;
while (true) {
while (SDL_PollEvent(&Event)) {
// ...
}
HandleKeyboard();
GameWindow.RenderFrame();
}
SDL_Quit();
return 0;
}
Space is not held
Space is not held
Space is not held
Space is held
Space is held
All the scan codes we need to index into this array are available in the SDK_keycode header file.
When our application doesn’t have input focus, the keyboard state array will be 0
in every position. That is, no key will be considered to be held down.
For SDL to update its keyboard state array, we must instruct it to process its event queue. In the previous examples, and in most applications, we’ve been doing that within our application loops.
Specifically, the continuous calls to SDL_PollEvent()
prompt SDL to keep its various components up to date, including the keyboard state array:
SDL_Event Event;
while (true) {
while (SDL_PollEvent(&Event)) {
// React to events
// ...
}
HandleKeyboard();
GameWindow.RenderFrame();
}
Even if we don’t need to react to the events, we still need to prompt SDL to process them at the appropriate time within the application loop.
However, if we don’t need to inspect the events, we can simplify our loop by using SDL_PumpEvents()
instead of SDL_PollEvent()
:
SDL_Event Event;
while (true) {
SDL_PumpEvents();
HandleKeyboard();
GameWindow.RenderFrame();
}
SDL_PumpEvents()
and SDL_PollEvent()
have a similar purpose, but are different in two key ways:
SDL_PumpEvents()
processes all the outstanding events on the queue, whilst SDL_PollEvent()
only handles one event per invocation. As such, we can remove the inner loop - we only need to call SDL_PumpEvents()
once per frame.SDL_PumpEvents()
doesn’t give us visibility of each individual event. As such, we can remove the argument, and delete the SDL_Event
variable it was based on.We’ve now seen two different approaches we can take to handle keyboard input. These designs are typically referred to as event-driven and polling:
Each design has its advantages and disadvantages and, in a more complex application, both techniques tend to be used.
Event-based designs tend to be preferred for interactions that are discrete rather than continuous. Examples of discrete actions include the user pressing a key to open up a menu, or clicking on a button in the UI.
Event implementations also tend to be more performant than polling, especially when the event is infrequent. Polling every frame to detect a state that rarely happens is usually a waste of resources, and is better implemented through the event queue.
Polling designs are more appropriate for interactions that tend to be continuous. For example, movement input is often implemented by the user holding down one of several designated keys.
In that scenario, having the movement system implement frame-by-frame polling to determine which movement keys are held down is typically cleaner than reacting to keydown and keyup actions coming from the event queue.
In this lesson, we explored how to handle keyboard input in SDL2 using both event-driven and polling methods. We learned how to obtain and interpret the keyboard state array to detect key presses.
SDL_GetKeyboardState()
function provides access to this array.Learn how to detect and handle keyboard input in SDL2 using both event-driven and polling methods. This lesson covers obtaining and interpreting the keyboard state array.
Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games