SDL 2.0 Tutorial-02: Almighty spritesheet

Last week we were able to create a window and renderer. This week we are going to read in a spritesheet image, separate it into individual 8×8 sprites and draw them to the screen.

First thing we need to do is read in the spritesheet. Here I’m using strict SDL2 so we’ll use the .bmp format with an alpha color key. Setting an alpha color key allows us to use an RGB value which acts as an alpha channel. When SDL looks over the image pixels and finds our RGB key it will replace the color with a transparent pixel. This saves on memory because instead of writing pixels in a 32-bit RGBA value we can use a 24-bit RGB value. This is only necessary if you are restricted to just SDL, ideally you would use the SDL2_image package. You can find out more about SDL2_image here.

Alright, let’s start by allocating memory for our “gfx” (graphics) module.

This takes our original Game “soliton” and adds a “gfx” module. The graphics module contains  unsigned int n;  which is the number of 8×8 sprites found within our .bmp spritesheet, and  SDL_Surface** spritesheet; which is an array of SDL surfaces. Each 8×8 sprite will receive its own SDL surface. Later we will arrange these surfaces into textures to be drawn with out renderer.

Next we will read in “spritesheet.bmp”, set the color key to 0xFF00FF and populate the spritesheet array with surfaces. This code should be placed within the  void game_init(void); function.

This will give us an array of sprite surfaces with the first sprite ( spritesheet[0] ) being a completely transparent surface. This is done on purpose so that the surface array an easily be integrated with the Tiled map editor, which we will discuss in future tutorials.

Next we will move to our  int main(int argc, char* argv[]); function where we will create textures for the sprites we wish to render. Ideally, the textures should be allocated for each room/level during the loading screen. This works well for a 2D game but isn’t required as most computers can handle the dynamic allocation without much problem. After modifying the code we are left with the following. If you would like to use the same spritesheet as I’m using here you can get it from here.

This will draw a chest in the middle of the screen. Here we are creating a texture for each 8×8 sprite. This is highly inefficient, what we will learn to do later is create a surface with all the 8×8 sprites and then create a texture from this bigger surface. This will help a lot but for now we are fine to do this. The last step here is to clean up the sprite array.

That’s it for now, at this point you should be able to play and experiment on your own, till next week. Good luck!




Leave a Reply

Your email address will not be published.