SDL2 Shooter 2 tutorial
SDL2 Widget tutorial
SDL2 Adventure tutorial
Orb source code
— 2D Top-down shooter tutorial —
Note: this tutorial series builds upon the ones that came before it. If you aren't familiar with the previous tutorials, or the prior ones of this series, you should read those first.
This first tutorial will explain how to read the mouse in SDL2. Unpack the code and then type make to build. Once compiling is finished type ./bad05 to run the code.
A 1280 x 720 window will open, with a dark grey background over which a multicolored grid is shown. A targetter will be displayed that will track the mouse movements. The main character, Donk, will also display. Donk can be moved with the WSAD control scheme and will always face the targetter. Use the left mouse button to fire. The mouse wheel will cycle through the available weapons. The right mouse button will reload the pistol when it is out of ammo. Enemies will appear in the arena and may drop powerups when defeated. Keep moving and try and stay alive as long as possible. Close the window by clicking on the window's close button.
Inspecting the code
There have been a number of additions to this part of the tutorial. The focus, however, is on scrolling the arena. Let's take a look at the additions made to enable this, starting, as always, with structs.h and defs.h:
In defs.h we've created defines for the size of the arena, and another two to help us with drawing the grid now that it is scrollable. In structs.h, we've also made an important addition:
The camera we'll be observing the game with will be stored as an SDL_Point (so, just x and y coordinates). So far so good. Now we've added a new compilation unit called camera.c. This is a very simple file with just one function:
doCamera is used to center the camera over the player. We do this by simply subtracting half the screen resolution from the player's position. This in itself isn't quite enough, but further calculations later on will help to remedy this. Note also that we're testing to see if player is null. We're doing this since, in this update, the player can now be killed by enemy fire.
Moving onto stage.c, we've made but one change to help with the camera display:
We call doCamera in our logic function so that the position is updated every frame. Now onto some more interesting things. In player.c we've had to make a tweak to the angle calculation:
Since the player can now walk around in the arena, we need to subtract the camera x and y from the player's x and y when calling getAngle. This is so that we can correctly resolve the player's position back to the screen location and not the arena location. If we don't do this, Donk will face completely the wrong way as we move around.
We'll see the need to carry out this same calculation when it comes to drawing the entities:
We subtract the camera's x and y from all the entities' x and y as we draw them, offsetting them correctly. Note that when Donk himself is drawn, he will be dead center in the screen, due to the calculation we did in doCamera. The same calculation is done with the bullets:
As well as subtracting the camera's x and y from the various entities while drawing them, we also need to make changes to the bullet function for when Donk fires:
Again, we need to subtract the camera's x and y from the bullet's when calculating the direction the bullet will go. If we fail to do this, Donk will not shoot in the correct direction, as he will attempt to shoot from the arena coordinates to the mouse's, which will be way off. The shotgun firing area projection needs to also be resolved:
Note that unlike firing the pistol and uzi, we need to only perform the camera calculation once (before the for loop). After that, we can happily tweak the pellets velocity and destination zone without impacting the aiming.
Finally, we want to scroll the background grid; it wouldn't look too good if the grid remained static as Donk and the enemies moved about. In order to do this, we make quite a number of changes to drawGrid in stage.c:
To start with, we need to decide where to render the grid from and to on both the x and y axis. We find the starting x and y (x1 and y1) by performing a modulo on the camera's x and y using the grid size, and then multiplying the result by -1. The means that the starting axis will be 0 or less, in effect meaning that the starting location could be offscreen. If we didn't multiply by -1, the x1 and y1 would always be positive and the starting tiles would keep popping in. Working out the ending x and y (x2 and y2) is a simple case of multiplying our grid render sizes by the grid size, and adding a final tile if we start at exactly 0 (again, to prevent the pop in effect).
Next, we want to work out our starting tiles. We do this by dividing the camera's x and y by our grid size and storing them in variables named mx and my. We then draw the grid by using for loops composed of x1, y1, x2, and y2. We increment mx and my as we step through their respective loops, resetting my at the end of its own. When it comes to drawing the grid tile itself, we check that mx and my are >= 0 than the size of the grid, and then draw it. To create a pattern we're simply multiplying mx and my together, dividing by 40 and then getting the modulo of 4, and using that as the tile image to draw. It's not a great, but it serves its purpose. Correctly handling a tile map will be discussed in another tutorial.
We've also added the ability for the enemies to attack Donk, new enemy types, and effects. We'll look at these briefly:
addEnemy now choosing between 3 different enemy types, with some enemies having a smaller chance of appearing than others. Each has their own texture, tick function, and health stats. They all share the same die function, however. Taking a look at one of the tick functions, we can see how the enemies are told to attack the player:
We check to see if the player is not null, and tell the enemy to chase Donk as usual. We then decrement the reload variable. Once this hits 0 or less, we test the distance between the player and the enemy. If it's less than half the screen height, we call the new fireEnemyBullet function and reset our reload counter, so that the enemy doesn't fire again right away. The fireEnemyBullet function is very simple:
It should be clear what is going on by now, as this is largely the same as when Donk fires his weapons. An Entity is created and all its essential details are filled in. The side set to SIDE_ENEMY, to prevent friendly fire from occurring, and the angle between the enemy and the player is calculated, as well as the direction of movement. Nothing unusual. One thing that is new is that the color of the bullet is being set. This is done using a new variable in the Entity struct:
SDL_Color is a simple struct that holds four values: r, g, b, and a, that should be set between 0 and 255 to set the intensity of the color, from dark to light.
We've also added effects for when bullets hit, and when enemies (and Donk) are killed. Another new struct is used for this:
Effect holds our location and direction details of our effect, as well as its color, texture, and how long it will live for. To handle effects, we've added a new compilation unit called effects.h. This contains a number of functions for creating, handling, and drawing effects. We'll look at one of the functions to add effects - addEnemyDeathEffect.
In practice, this function will create a number of squares (128 of them..!) that spread out from the center of the enemy. As can be seen, we create a for loop to malloc 128 Effects, set each one to the enemy's (self) coordinates, give them a random dx and dy, and a random color between red and yellow. We also set the alpha of the color (color.a) to somewhere between 0 and 255. This will mean that when we come to draw the effects, they will show at various states of transparency. We also set to life to be somewhere between 0 and 1 second. The texture is a small white square, 16x16 pixels (whiteSquare16), that is a static variable within effects.c.
The logic for our effects is done by doEffects:
This function will simply step through all the effects, adding their dx and dy to their x and y, decreasing their life, and removing them once their life hits 0. One other thing we do is decrease their alpha (color.a), limiting it to 0. This will make the effects fade away as they age. Finally, let's look at drawEffects:
This is where our colors and alpha come into play. We tell SDL to use an additive blend mode by calling SDL_SetRenderDrawBlendMode with SDL_BLENDMODE_ADD and passing over renderer. We tell the texture of the effect to also use an additive blend mode, then set the color and alpha information of the texture to that held by the effect. With this done, we draw the effect by calling our blit function, subtracting the camera x and y as we do, and telling the texture to be centered about those coordinates. Once done, we set the renderer's blend mode back to SDL_BLENDMODE_NONE to prevent any ill effects.
Finally, to bring this all together, we need to initialize various bits and pieces (such as loading and caching textures). We can do this in init.c, in initGame:
Battle Arena Donk! is almost finished. In the final part of this tutorial we'll add the finishing touches, such as sound effects, a title screen, highscore table, and some other tweaks.
The source code for all parts of this tutorial (including assets) is available here:
It is also available as part of the SDL2 tutorial bundle (with on-going updates):