
When implementing controller support in a game, it’s desirable for gamepads to just work without a lot of user configuration. Platform APIs are pretty useless for this; the solution is an API like SDL’s Gamepad API that allows you to target a large number of gamepads without much effort.
Each operating system has its own API for gamepad input. Windows has XInput, and Linux has the joystick and evdev APIs. When a gamepad button is pressed, applications will receive a button id. This is a number, there’s no OS way to know which button id corresponds with which button. The ids for a button are not the same on different gamepads and platforms, making it super hard to support more than a couple of devices.
SDL3
if (SDL_GetJoystickButton(joystick, 8)) {
std::cerr << "no idea what button 8 is" << std::endl;
}SDL2
if (SDL_JoystickGetButton(joystick, 8)) {
std::cerr << "no idea what button 8 is" << std::endl;
}One thing platforms do give you is the name, model, and manufacturer of the game controller. If you test with a large number of gamepads, you can create a database from gamepad name to layout. Luckily, SDL has already done this for you. Instead of a random number, you can use a named button that will work no matter the gamepad and platform:
SDL3
if (SDL_GetGamepadButton(gamepad, SDL_GAMEPAD_BUTTON_SOUTH)) {
std::cerr << "The bottom face button (A on Xbox) was pressed!" << std::endl;
}SDL2
if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_A)) {
std::cerr << "The bottom face button (A on Xbox) was pressed!" << std::endl;
}This article was originally written for SDL2’s SDL_GameController API. It
has now been updated for SDL3. If you’re updating from SDL2 to 3, see
SDL’s migration guide.
What is the SDL Gamepad API? #
SDL_Gamepad (called SDL_GameController in SDL2) is an abstraction that
allows you to program input based on an Xbox-like controller layout, and have it
work with a huge variety of devices. It’s a layer built on top of the raw
SDL_Joystick API.
Xbox-like controllers have a DPAD, two analog sticks, 4 buttons on the right (eg: A/B/X/Y), shoulder buttons, and 3 buttons in the middle (start/back/logo). Examples include PlayStation DualShock and DualSense, Nintendo Switch Pro, and Steam Deck.
Mapping #
SDL comes with a database of game controllers, mapping from controller id to layout information.
Users can provide custom mappings using the SDL_GAMECONTROLLERCONFIG
environment variable. If you want to support even more controllers, you can ship
custom binding files with your game, such as the community
SDL_GameControllerDB, and
load them after initialising SDL:
SDL3
SDL_AddGamepadMappingsFromFile("gamecontrollerdb.txt");SDL2
SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");Steam also comes with built-in support for SDL’s gamepad API, allowing users to remap their controllers for your game in Steam. If Steam supports the controller, your game will too.
Using the SDL Gamepad API #
Setup #
When initializing SDL, add the SDL_INIT_GAMEPAD flag
(SDL_INIT_GAMECONTROLLER in SDL2):
SDL3
#include <SDL3/SDL.h>
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD)) {
std::cerr << "SDL could not initialize! SDL Error: " << SDL_GetError()
<< std::endl;
return 1;
}SDL2
#include <SDL2/SDL.h>
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) < 0) {
std::cerr << "SDL could not initialize! SDL Error: " << SDL_GetError()
<< std::endl;
return 1;
}SDL3 identifies gamepads using an SDL_JoystickID instance id, rather than
SDL2’s device index. Make sure to SDL_free the array returned by
SDL_GetGamepads. In SDL2, you loop through the joystick device indices
instead:
SDL3
SDL_Gamepad *findGamepad() {
int count = 0;
SDL_JoystickID *ids = SDL_GetGamepads(&count);
SDL_Gamepad *gamepad = count > 0 ? SDL_OpenGamepad(ids[0]) : nullptr;
SDL_free(ids);
return gamepad;
}SDL2
SDL_GameController *findController() {
for (int i = 0; i < SDL_NumJoysticks(); i++) {
if (SDL_IsGameController(i)) {
return SDL_GameControllerOpen(i);
}
}
return nullptr;
}For simplicity, we’ll only be setting up and tracking a single gamepad at a time. But it’s a similar process to handle multiple gamepads.
SDL3
SDL_Gamepad *gamepad = findGamepad();SDL2
SDL_GameController *controller = findController();Gamepad connection and removal #
Next, you’ll need to listen for the SDL_EVENT_GAMEPAD_ADDED and
SDL_EVENT_GAMEPAD_REMOVED events in the event loop. SDL also sends
SDL_EVENT_GAMEPAD_ADDED for gamepads that were already connected at startup.
SDL3
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_EVENT_GAMEPAD_ADDED:
if (!gamepad) {
gamepad = SDL_OpenGamepad(event.gdevice.which);
}
break;
case SDL_EVENT_GAMEPAD_REMOVED:
if (gamepad && event.gdevice.which == SDL_GetGamepadID(gamepad)) {
SDL_CloseGamepad(gamepad);
gamepad = findGamepad();
}
break;
}
}SDL2
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_CONTROLLERDEVICEADDED:
if (!controller) {
controller = SDL_GameControllerOpen(event.cdevice.which);
}
break;
case SDL_CONTROLLERDEVICEREMOVED:
if (controller && event.cdevice.which == SDL_JoystickInstanceID(
SDL_GameControllerGetJoystick(controller))) {
SDL_GameControllerClose(controller);
controller = findController();
}
break;
}
}In SDL3, the which field is the instance id of the gamepad for both events.
SDL2 is more awkward: the added event gives you a device index, whereas the
removed event gives you the joystick instance id. To check whether the removed
controller is yours, you first need to get the SDL_Joystick and then its
instance id.
Handling input #
There are two ways of receiving input; you can either use events or you can poll for input state. The following events are available:
- Device Events:
SDL_EVENT_GAMEPAD_ADDED: A gamepad was added.SDL_EVENT_GAMEPAD_REMOVED: A gamepad was removed.SDL_EVENT_GAMEPAD_REMAPPED: A gamepad was remapped, you can mostly ignore this event unless you use raw joysticks.
- Button Events:
SDL_EVENT_GAMEPAD_BUTTON_DOWN: A button was pressed on a gamepad.SDL_EVENT_GAMEPAD_BUTTON_UP: A button was released on a gamepad.
- Axis Events:
SDL_EVENT_GAMEPAD_AXIS_MOTION: An axis was moved, such as a thumbstick or analog trigger.
- Sensor Events:
SDL_EVENT_GAMEPAD_SENSOR_UPDATE: A gyro or accelerometer was updated.
- Touchpad Events:
SDL_EVENT_GAMEPAD_TOUCHPAD_DOWN,SDL_EVENT_GAMEPAD_TOUCHPAD_MOTION, andSDL_EVENT_GAMEPAD_TOUCHPAD_UP: A finger touched, moved on, or left a touchpad, like the one on the PS5 DualSense.
- Capacitive Sensing Events
(SDL 3.6+):
- Capacitive touch sensing, for example, detecting a thumb resting on a thumbstick.
SDL2 has equivalents for all of these except capacitive sensing, named like
SDL_CONTROLLERBUTTONDOWN. Sensor and touchpad events need SDL 2.0.14 or later.
Here’s an example of handling the bottom face button using the event:
SDL3
case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
if (gamepad && event.gbutton.which == SDL_GetGamepadID(gamepad)) {
switch (event.gbutton.button) {
case SDL_GAMEPAD_BUTTON_SOUTH:
std::cerr << "South pressed!" << std::endl;
break;
}
}
break;SDL2
case SDL_CONTROLLERBUTTONDOWN:
if (controller && event.cbutton.which == SDL_JoystickInstanceID(
SDL_GameControllerGetJoystick(controller))) {
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_A:
std::cerr << "A pressed!" << std::endl;
break;
}
}
break;and by polling for input state:
SDL3
if (SDL_GetGamepadButton(gamepad, SDL_GAMEPAD_BUTTON_SOUTH)) {
std::cerr << "South is held down!" << std::endl;
}SDL2
if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_A)) {
std::cerr << "A is held down!" << std::endl;
}Positional buttons: South, East, West, and North #
SDL2 named the face buttons after the Xbox layout: A, B, X, and Y. This was confusing as a Nintendo controller has A and B the other way around. SDL3 names the face buttons by their position instead:
| SDL3 | Xbox | PlayStation | Nintendo |
|---|---|---|---|
SDL_GAMEPAD_BUTTON_SOUTH |
A | Cross | B |
SDL_GAMEPAD_BUTTON_EAST |
B | Circle | A |
SDL_GAMEPAD_BUTTON_WEST |
X | Square | Y |
SDL_GAMEPAD_BUTTON_NORTH |
Y | Triangle | X |
To show the correct button prompts in your UI, you can ask SDL what the button is labelled on the connected gamepad. SDL2 doesn’t have a label API, so you’ll need to work it out from the controller type instead:
SDL3
const char *getButtonName(SDL_Gamepad *gamepad, SDL_GamepadButton button) {
switch (SDL_GetGamepadButtonLabel(gamepad, button)) {
case SDL_GAMEPAD_BUTTON_LABEL_A: return "A";
case SDL_GAMEPAD_BUTTON_LABEL_B: return "B";
case SDL_GAMEPAD_BUTTON_LABEL_X: return "X";
case SDL_GAMEPAD_BUTTON_LABEL_Y: return "Y";
case SDL_GAMEPAD_BUTTON_LABEL_CROSS: return "Cross";
case SDL_GAMEPAD_BUTTON_LABEL_CIRCLE: return "Circle";
case SDL_GAMEPAD_BUTTON_LABEL_SQUARE: return "Square";
case SDL_GAMEPAD_BUTTON_LABEL_TRIANGLE: return "Triangle";
default: return "Unknown";
}
}SDL2
const char *getButtonName(SDL_GameController *controller,
SDL_GameControllerButton button) {
switch (SDL_GameControllerGetType(controller)) {
case SDL_CONTROLLER_TYPE_PS3:
case SDL_CONTROLLER_TYPE_PS4:
case SDL_CONTROLLER_TYPE_PS5:
switch (button) {
case SDL_CONTROLLER_BUTTON_A: return "Cross";
case SDL_CONTROLLER_BUTTON_B: return "Circle";
case SDL_CONTROLLER_BUTTON_X: return "Square";
case SDL_CONTROLLER_BUTTON_Y: return "Triangle";
default: return "Unknown";
}
default:
// By default, SDL2 maps Nintendo controllers by label rather than
// position (SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS), so the
// letters match for Xbox and Nintendo controllers.
switch (button) {
case SDL_CONTROLLER_BUTTON_A: return "A";
case SDL_CONTROLLER_BUTTON_B: return "B";
case SDL_CONTROLLER_BUTTON_X: return "X";
case SDL_CONTROLLER_BUTTON_Y: return "Y";
default: return "Unknown";
}
}
}You can use SDL_GetGamePadType (SDL_GameControllerGetType in SDL2) to find
out whether the gamepad is an Xbox, PlayStation, or Switch controller. This is
useful to show control glyphs based on the gamepad type.
Analog sticks and triggers #
Thumbsticks and triggers are axes. SDL_GetGamepadAxis
(SDL_GameControllerGetAxis in SDL2) returns a value between -32768 and 32767
for sticks, and between 0 and 32767 for triggers. For the Y axis of a stick,
negative values are up.
Thumbsticks rarely rest at exactly zero, so you’ll need to apply a deadzone to avoid the player drifting when the stick isn’t touched. Here’s a helper that converts an axis to a value between -1 and 1, with a deadzone:
SDL3
#include <algorithm> // std::clamp, requires C++17
#include <cmath> // std::abs
float getAxis(SDL_Gamepad *gamepad, SDL_GamepadAxis axis) {
const float DEADZONE = 0.2f;
float value = SDL_GetGamepadAxis(gamepad, axis) / 32767.0f;
value = std::clamp(value, -1.0f, 1.0f);
if (std::abs(value) < DEADZONE) {
return 0.0f;
}
// Rescale so the output starts at 0 at the edge of the deadzone,
// rather than jumping straight to 0.2
float sign = value < 0 ? -1.0f : 1.0f;
return sign * (std::abs(value) - DEADZONE) / (1.0f - DEADZONE);
}
float moveX = getAxis(gamepad, SDL_GAMEPAD_AXIS_LEFTX);
float moveY = getAxis(gamepad, SDL_GAMEPAD_AXIS_LEFTY);
float accelerate = getAxis(gamepad, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER);SDL2
#include <algorithm> // std::clamp, requires C++17
#include <cmath> // std::abs
float getAxis(SDL_GameController *controller, SDL_GameControllerAxis axis) {
const float DEADZONE = 0.2f;
float value = SDL_GameControllerGetAxis(controller, axis) / 32767.0f;
value = std::clamp(value, -1.0f, 1.0f);
if (std::abs(value) < DEADZONE) {
return 0.0f;
}
// Rescale so the output starts at 0 at the edge of the deadzone,
// rather than jumping straight to 0.2
float sign = value < 0 ? -1.0f : 1.0f;
return sign * (std::abs(value) - DEADZONE) / (1.0f - DEADZONE);
}
float moveX = getAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
float moveY = getAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
float accelerate = getAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);This applies the deadzone to each axis separately. For smoother movement in all directions, you should instead apply the deadzone to the (moveX, moveY) vector.
Conclusion #
Using SDL’s Gamepad API, it’s possible to target a large number of gamepads on different platforms without much effort. How to manage multiple gamepads, keyboard and mouse, and input binding is definitely a story for another time.
Take a look at the complete example code on Codeberg for SDL3 and SDL2.
Sources #
Image © 2019 Stas Knop
Comments