Today, I'll show you a way to easily manage keypresses with SDL2 and C. Setting up keypresses can get pretty messy sometimes, with code cluttered with a multitude of if/else if/else
statements or switch
statements, like this:
However, there's a much easier way of checking for keypresses, and this is how you do it. First, let's setup a basic C project. Create a file called main.c
and put these three headers at the top:
#include <stdio.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
Next, create the classic int main
function, like so:
int main() {
return 0;
}
Next, let's set up a typedef struct
called "Game." Inside it, we'll put an array labeled input,
like so:
typedef struct {
int input[256];
}, Game;
Game game = {
.input = {}
};
Next, let's create a function called handle_input
. We'll prototype it at the top like so
void handle_input();
and declare it below int main()
:
void handle_input() {
}
Inside of this function, we can put the SDL_Event structure, labeled event
, like so:
void handle_input() {
SDL_Event event;
}
Now, we can check if the key is being pressed or released, with these two conditionals, utilizing the array that we created earlier:
void handle_input() {
SDL_Event event;
if (event.type == SDL_KEYDOWN) {
game.input[event.key.keysym.scancode] = true;
//printf("Keydown");
}
if (event.type == SDL_KEYUP) {
game.input[event.key.keysym.scancode] = false;
//printf("Keyup");
}
}
The code above will check if a key is down. If so, the game.input array will be assigned true, and if the key is up, then the game.input array will be assigned false. Inside the array, we've put event.key.keysym.scancode
, which allows us to check any SDL_key we want.
So, now that the handle_input
function is done, we can test this out. Call handle_input()
in the int main()
function. Now, all we need to do to check if a key is pressed, say the "R" key, is do this, within the int main()
or any other function:
if (game.input[SDL_SCANCODE_R]) {
//Do something!
}
That's it! It's so much neater and cleaner, and with this approach we can check any key we want without creating an if statement or a switch statement for every single key we want to use.
Please note: the code will not work by itself, you may setup an SDL2 window to test it out.
Thanks for reading, and happy coding!!
Top comments (0)