Repository navigation
Chapter 3 ‐ Fetching Input
Today we are going to sample the input data in the client.
As mentioned earlier, we are going to implement a very simply input scheme. We stick to the GameBoy input with 4 actions buttons, 4 direction buttons. This means you have 8 buttons in total which can be either pressed or released. So you can use 1 bit for each button representing its state and 8-bits (which fits conveniently in a single byte) for all buttons.
For convenience we define the bit-patterns for our buttons like this:
// button bit-masks
typedef enum {
BUTTON_A = 1,
BUTTON_B = 2,
BUTTON_X = 4,
BUTTON_Y = 8,
BUTTON_UP = 16,
BUTTON_DOWN = 32,
BUTTON_LEFT = 64,
BUTTON_RIGHT = 128,
} button_t;Actually this section is super easy. It's mainly enhancing the handle_SDL_events function to take action on mouse clicks, keyboard pressed and gamepad presses. The latter is very nice as SDL2 supports almost any game controller on the world and remaps it to a standard XBox360 controller. So you always have A, B, X, Y, Up, Down, Left, Right.

Honestly this is just a series of switch statements in order to get the button mapping like this:
| Button | Keyboard | Mouse | Controller | Bit-Mask |
|---|---|---|---|---|
| A | Enter, I | Left | A | 1 |
| B | Space, O | Right | B | 2 |
| X | K | X | 4 | |
| Y | L | Y | 8 | |
| Up | W, 8 | Up | 16 | |
| Down | S, 2 | Down | 32 | |
| Left | A, 4 | Left | 64 | |
| Right | D, 6 | Right | 128 |
All those keys, mouse buttons, gamepad buttons will end up in this function which flips the bits in our 8-bit input mask:
// apply a button state
static void apply_button(const button_t button, const bool down) {
if (down) {
state.input.down |= button;
} else {
state.input.down &= ~button;
}
}As a small side note here. You have to "open" a gamecontroller when SDL emits a "controller added" event. Note that there is no error handling, but it should work anyways.
case SDL_CONTROLLERDEVICEADDED: SDL_GameControllerOpen(ev.cdevice.which); break;You can see the whole source here.