DEV Community

Samuel Collier
Samuel Collier

Posted on

Easy Start with SDL2

Getting setup with SDL2 can be quite difficult. Getting the editor setup is easy enough, but what is the best way to create a window? How should we handle input? How do we compile it?

However, in an attempt to help, I've created this Github repository to easily set up a SDL2 project with a window, user input, and compilation already done.

You can find the repository here.

The code is pretty self explanatory, but I'll go over a few things. Firstly, all the main components of the window are located in a struct called Game. (This struct is located in the global scope, but you can change that if you like, and pass Game* game as a parameters to the functions.)

With this struct, to access the window, just type game.window, or to access the renderer, just type game.renderer. (If struct is not global, do game->window, etc.)

Notice that there are also two functions, initialize() and handle_input(). initialize() just creates a window and sets up the renderer; handle_input(), however, allows you to easily check user input, by typing a conditional like so:

if (game.input[**SDL_SCANCODE_KEY**]) {
    //Do something
}
Enter fullscreen mode Exit fullscreen mode

I created another article explaining this in more detail here.

Finally, to compile (with linux), make sure you have the GCC compiler installed, go to the project directory, type cd build (to get into the build directory), and type sh run.sh. The compile commands are already set up in the SH file. The result should look something like this:

Image description

If you have some trouble setting this up, I have a visual example (no audio) linked here.

Anyways, I hoped you enjoyed this quick overview and find the repository useful. Happy coding!!

Top comments (0)