• 2D shoot 'em up
SDL2 Santa game tutorial 🎅
SDL2 Shooter 3 tutorial
The Legend of Edgar 1.36
SDL2 map editor tutorial [UPDATED]
TBFTSS: The Pandoran War - Amiga OS4 Port
— 2D Shoot 'Em Up Tutorial —
Note: this tutorial builds upon the ones that came before it. If you aren't familiar with the previous tutorials in this series you should read those first.
We can shoot the enemies to destroy them, but right now they just vanish. That's no fun. How about we make them explode, instead? Extract the archive, run cmake CMakeLists.txt, followed by make to build. Once compiling is finished type ./shooter09 to run the code.
A 1280 x 720 window will open, with a colorful background. A spaceship sprite will also be shown, as in the screenshot above. The ship can now be moved using the arrow keys. Up, down, left, and right will move the ship in the respective directions. You can also fire by holding down the left control key. Enemies (basically red versions of the player's ship) will spawn from the right and move to the left. Shoot enemies to destroy them. Enemies can fire back, so you should avoid their shots. Close the window by clicking on the window's close button.
Inspecting the code
This update could be summarized as the "prettification" stage. Because we've added effects such as explosions, debris, a starfield, and a scrolling background, there have been a considerable number of new additions made. This update is therefore longer than most. We'll start by taking a look at the changes made in structs.h and defs.h.
In structs.h we've added two new declarations:
Explosion will be used to hold details of an explosion, while Debris will do the same for debris that is thrown when a ship is destroyed. Both are linked lists and are introduced into the Stage object. We're also declaring a Star object, as part of that the starfield we'll be making. We'll detail these fully when we get to stage.c.
Next, let's look at defs.h:
Were adding a starfield to the game and will be handling the stars as a fixed sized array, rather than a linked list. We'll put 500 stars on screen at a time (it may sound a lot, but screen resolution means that with only a handful they would not be too visible). Onto draw.c, where a new function has been added:
blitRect is a second blit function (note: it doesn't replace the existing one). As well as taking a texture and coordinates, it also takes a rectangular region as the second argument. This is used to tell the SDL_RenderCopy function what portion of the source texture we want to draw. This means that we don't have to draw the entire source texture on screen, and can pick and choose what to display. The dest rect takes src rect's w and h as its width and height, and then both src and dest are passed to SDL_RenderCopy. We're going to be using this in stage.c when we come to destroying the ships; they'll be broken into pieces when destroyed, so we'll tell our game to pick some rectangular regions of the source sprite to work with.
As always, it is stage.c that has seen the bulk of the updates:
In the initStage function we're now loading a background graphic and a new explosion texture (as well as setting up the explosion and debris linked lists). Nothing major. resetStage also sees some minor updates:
We're clearing down the linked lists, as expected, but are also calling a new function called initStarfield. You'll notice we're also extending the stage reset time to 3 seconds. This is so that we can better appreciate the player being killed and throwing their own debris about the screen.
Moving onto the first new function initStarfield, we can see that things are quite simple:
We loop through all our stars array (this array can be found a static variable in stage.c) and randomly assigning them positions about the entire screen. We also give them a random speed, from 1 to 3. This speed will not only affect how fast they move but also how bright they appear when we come to draw them.
We'll deal with all the updates to the logic phase of the game now, beginning with the main logic function.
We're calling four new functions here: doBackground, doStarfield, doExplosions, and doDebris. We'll cover these in order, starting with doBackground:
The doBackground function simply decrements a variable called backgroundX (local to stage.c), resetting it to 0 if it reaches negative SCREEN_WIDTH (so, about -1280). This means that, when drawing it, the background will wrap around. More on this when we come to drawing. Onto doStarfield:
Nothing out of the ordinary here. We're looping through our stars array and decreasing the star's x value according to speed. When the value of x is less than 0 we'll return it to the other side of the screen. One little thing we're doing is taking into consideration what the negative value was at the time, rather than setting the star's x exactly to SCREEN_WIDTH. This should help to avoid a situation where the stars could all start to line up over time.
doExplosions is the next new function, and again nothing too taxing to consider:
This function is basically stepping through our list of explosions, moving them according to their dx and dy (to make the explosion appear to be spreading out, rather than sitting in the same place), and decrementing the value of their a variable. The a variable holds the explosion's alpha value. Decrementing this means that the explosion will become less visible as time goes on (we'll cover this when we come to drawing the explosions). When the a value is 0, we'll delete the explosion.
Looking next at doDebris, we'll not see anything too wildly different:
Each of our debris items is moved according to their dx and dy, their life decremented, and the debris item deleted when it falls to 0. One small thing we're doing here is increasing the dy value by 0.5. This means that the debris will accelerate down the screen each frame, giving the impression of it falling due to gravity (which is odd, given that we're in space, but hey, they did it in The Last Jedi, right..?).
Let's move onto something more interesting - a function to add explosions:
This function accepts three parameters: the x and y of the origin of the explosion, and the number of explosion effects we want to add (num). We use a for loop to malloc num number of explosions, setting each one's attributes. The explosion's x and y are set to the ones we passed into the function, plus/minus a random 32 pixels in each direction. We also set the explosion's dx and dy to between plus/minus 9, dividing by 10 to give us -0.9/0.9 so that the explosion doesn't move around too fast. Finally, we set the explosion to a random colour of red, orange, yellow, or white, assigning the explosion's r, g, and b variables to the appropriate value of 255 (SDL colour values go between 0 and 255, from none to full). We also set the explosion's a (alpha) to a random amount of 0 to 3 seconds, governing how long it will live for.
The new addDebris function will be used to shatter our ship into pieces when it's destroyed. We pass over the Entity we wish to work with:
We want to quarter our entity and throw four pieces of debris. First, we divide the entity's w and h by two, then create a for loop across the x and y (incrementing by the w and h values we calculated). We malloc a piece of Debris, setting each one's x and y to the centre of the source entity, and also giving each a random dx velocity. The dy velocity will always be a negative between -5 and -16, meaning that the debris will travel up screen to begin with. If you remember from our doDebris function, the debris will soon begin to move back down. This will give the debris the impression of being thrown up. We set the debris' life to 2 seconds and the texture to that of the source entity. Now comes the important bit: the debris object contains an SDL_Rect which we'll use to hold the texture coordinates. We set the rect's x and y to those of our for loop, and the w and h to the w and h we worked out earlier. In effect, we'll get the texture coordinates of our source texture in quarters.
With all our new logic and processing dealt with, we can move onto the rendering phase:
To our draw function we've added code to draw the background, starfield, debris, and explosions. We'll go through the in order:
The drawBackground function draws our background texture using the backgroundX variable and the SDL_RenderCopy function. Because backgroundX is being decremented, it could be negative and therefore not cover the entire screen. Therefore, we set up a for loop to draw the background again, offset where the previous draw command ended. There is an optimisation we could be doing here: only drawing the portions of the background that we actually need. While this might be done in a later tutorial, right now it will be left an exercise for the reader. Something to notice is how we're setting dest's w and h to SCREEN_WIDTH and SCREEN_HEIGHT. We're doing this because our background texture is smaller than the screen (about 512 x 512). We're therefore stretching it to make it fit.
Next, we come to drawStarfield:
As can be seen, we're stepping through each of our stars in the array. We want to draw the stars as a horizontal line. What we're doing is calling SDL_SetRenderDrawColor to set the colour of the line according to the speed of the star (the higher the speed of the star, the brighter the color). The SDL_SetRenderDrawColor function takes four arguments: the renderer, and the red, green, blue, and alpha values (between 0 and 255 each). The SDL_RenderDrawLine function takes five parameters: the renderer, and the starting x,y and end x,y of the line we want to draw. We use a line instead of a point to make the stars a little easier to see and provide a sense of speed to the proceedings.
Our drawDebris function comes next. This is where we'll use our new blitRect function:
As expected, this function loops through each debris item, drawing it according to the portion of the texture that we set up earlier. Nothing particularly out of the ordinary.
Finally, let's look at the drawExplosions function. This is where things get a little more interesting:
If you've looked at the explosion texture in the source code (gfx/explosion.png) you'll see that it's a black and white gradiated sphere, lighter in the middle, growing darker as it expands out. What we'll be doing to create an explosion effect is colouring this texture and blending the results together to make a convincing glow-type effect. First, we'll call SDL_SetRenderDrawBlendMode, telling it to use SDL_BLENDMODE_ADD. This is additive blending, meaning that as we layer textures upon one another the colour of the affected pixels will add together, becoming brighter (and eventually reaching white). We also tell our explosion texture itself to also be SDL_BLENDMODE_ADD. We then loop through each item in our explosion list and set the colour and alpha of the explosionTexture to that of the object (which we did when we created them in addExplosions). Finally, we blit our explosionTexture as normal. We also reset the app.renderer's blend mode to SDL_BLENDMODE_NONE, to avoid any ill effects.
One final thing we want to do is hide the mouse cursor, so it's not in the way. We do this in initSDL:
We can turn it back on at any time by calling SDL_ShowCursor(1).
And that's it for all our effects. The game is now more attractive to look at and play, and the explosions and debris are rather pleasing. More effects could be added, such as engine trails behind the ships and making the debris trail fire, but right now these will be left as an exercise for the reader.
You've probably noticed by now that the stage.c file is getting rather big; it is currently over 700 lines. This is fine for our tutorial, but if we were expanding this into a much larger game, we'd want to push the debris and explosion functions into their own compilation unit (and probably all the stuff to deal with the bullets, the player, and the enemies). Having said so, this might happen in a later update.
The source code for all parts of this tutorial (including assets) is available for purchase:
It is also available as part of the SDL2 tutorial bundle:
 - Dear god, that film was so bad.