PC Games

Orb
Lasagne Monsters
Three Guys Apocalypse
Water Closet
Blob Wars : Attrition
The Legend of Edgar
TBFTSS: The Pandoran War
Three Guys
Blob Wars : Blob and Conquer
Blob Wars : Metal Blob Solid
Project: Starfighter
TANX Squadron

Tutorials

2D shoot 'em up
2D top-down shooter
2D platform game
Sprite atlas tutorial
Working with TTF fonts
2D adventure game
Widget tutorial
2D shoot 'em up sequel
2D run and gun
Roguelike
Medals (Achievements)
2D turn-based strategy game
2D isometric game
2D map editor
2D mission-based shoot 'em up
2D Santa game
2D split screen game
SDL 1 tutorials (outdated)

Latest Updates

SDL2 Versus game tutorial
Wed, 20th March 2024

Download keys for SDL2 tutorials on itch.io
Sat, 16th March 2024

The Legend of Edgar 1.37
Mon, 1st January 2024

SDL2 Santa game tutorial 🎅
Thu, 23rd November 2023

SDL2 Shooter 3 tutorial
Wed, 15th February 2023

All Updates »

Tags

android (3)
battle-for-the-solar-system (10)
blob-wars (10)
brexit (1)
code (6)
edgar (9)
games (43)
lasagne-monsters (1)
making-of (5)
match3 (1)
numberblocksonline (1)
orb (2)
site (1)
tanx (4)
three-guys (3)
three-guys-apocalypse (3)
tutorials (17)
water-closet (4)

Books


The Attribute of the Strong (Battle for the Solar System, #3)

The Pandoran War is nearing its end... and the Senate's Mistake have all but won. Leaving a galaxy in ruin behind them, they set their sights on Sol and prepare to finish their twelve year Mission. All seems lost. But in the final forty-eight hours, while hunting for the elusive Zackaria, the White Knights make a discovery in the former Mitikas Empire that could herald one last chance at victory.

Click here to learn more and read an extract!

Basic Tutorials

Basic Game Tutorial #5 - Firing bullets

Introduction

Now that we can move a sprite around the screen, we will look into firing bullets. These tutorials will go into less detail about loading images and sounds because they have been covered in earlier tutorials and the theory is essentially the same.

Compile and run tutorial05. You can control the ship by using the arrow keys (not the ones on the numeric pad). Pressing the space key will fire a bullet, which will move to the right from the ship's current position.

An in-depth look

To deal with the player and the bullets, we update the Entity structure as follows:

typedef struct Entity
{
    int active;
    int x, y, thinkTime;
    SDL_Surface *sprite;
    void (*action)(void);
    void (*draw)(void);
} Entity;
We will be creating an array of Entities so the easiest way to determine whether an Entity is being used is to set a variable stating this. If the active variable is 0 then this Entity is not being used and can therefore be used to create a new bullet or whatever we want to create from it. The thinkTime variable is a timer that, in this tutorial is used to limit the number of bullets we can fire per second. action and draw are simply function pointers to our action and drawing functions respectively.

The Control function has another value, fire which is used to let us know that we want to attempt to fire a bullet.

We will first look at entites.c. This file has 5 functions in it. We will look at these one at a time.
The clearEntities function loops through all of the available Entities and marks them as inactive using the C function memset. This ensures that at the start of the program, there are empty slots to fire bullets. In a larger game you would need to reset everything at the start of a level to make sure that when it starts there aren't enemies, bullets etc. appearing randomly on the screen.

getFreeEntity is a function that will be commonly used. It will loop through all the available Entities and return the index of the first one it finds that is marked as inactive. It will also initialise the Entity to ensure that all of its variables and functions are set to 0. If the function cannot find a free Entity, it will return -1 and you would deal with it as appropriate. In our code we will simply flag an error and carry on.

doEntities is used in the main game loop. This function loops through all the Entities and point its memory address to the self Entity global pointer, which we will go into more detail later on. If the Entity is marked as active, we call its action function.

drawEntities is exactly the same as doEntities, except that we call the draw function instead.

The drawStandardEntity function is similar to the drawPlayer functions from previous tutorials. Note that we are using the self pointer in this function. You will see how this is used later.

In input.c we add add the reading of the space key to the inputs.

We'll now look at player.c, specifically the doPlayer function. At the start of the function we decrease the player's thinkTime, and if it is less than or equal to 0, we set it to 0.

player.thinkTime--;

if (player.thinkTime <= 0)
{
    player.thinkTime = 0;
}
The thinkTime is what controls the player's ability to fire bullets. We constantly decrease this value in each loop until it reaches 0. We must stop it from simply decreasing continously as the integer value would eventually wrap around and then the player would not be able to fire a bullet for a very long time (since it would then become positive again). The rest of the code is the same apart from the reading of the fire button:
if (input.fire == 1)
{
    /* You can only fire when the thinkTime is 0 or less */

    if (player.thinkTime <= 0)
    {
        addBullet(player.x + player.sprite->w, player.y + (player.sprite->h / 2));

        player.thinkTime = MAX_RELOAD_TIME;
    }
}
When the program detects the space key, it will then attempt to fire a bullet. A bullet can only be fired if the thinkTime is 0 or less, so if this is true the we call the addBullet function. This function takes the starting x and y coordinates, which we set to the right hand side of the player's sprite and roughly halfway down the player's height respectively. We will look into this function in more detail later. Once we have fired a bullet, we set the thinkTime back to the MAX_RELOAD_TIME, otherwise the player would be able to fire again immediately afterwards. The lower the value is for MAX_RELOAD_TIME, the sooner the player will be able to fire another bullet. The inverse is also true, so try changing this value to see what happens. It is in defs.h.

bullet.c handles the creation and movement of the bullets. We will look at each of the functions in this file in turn:

void addBullet(int x, int y)
{
    int i = getFreeEntity();

    if (i == -1)
    {
        printf("Couldn't get a free slot for a bullet!\n");

        return;
    }

    entity[i].x = x;
    entity[i].y = y;
    entity[i].action = &moveStandardBullet;
    entity[i].draw = &drawStandardEntity;
    entity[i].sprite = getSprite(BULLET_SPRITE);

    /* Play a sound when the shot is fired */

    playSound(BULLET_SOUND);
}
The addBullet function first gets a free Entity by calling the getFreeEntity function. If we get back -1 then we ran out of Entities to create bullets from so we will just log the error to the console and return. Using the index number we get back we set the Entity's x and y using the values passed in. For the action, we set this to the moveStandardBullet function found later on in this file. We use drawStandardEntity for the draw function which we covered earlier in the tutorial. We also set the sprite to the BULLET_SPRITE. Finally, we call the playSound function to play the sound of a bullet being fired.
The second function, moveStandardBullet is the function called when the bullet's action function is called. Note that we use the self pointer which means that we don't need to track the Entity itself and we can also manipulate the values without having to return anything.
static void moveStandardBullet()
{
    /* Move the bullet across the screen */

    self->x += BULLET_SPEED;

    /* Kill the bullet if it moves off the screen */

    if (self->x >= SCREEN_WIDTH)
    {
        self->active = 0;
    }
}
The function is simple enough, the bullet will move at the speed defined by BULLET_SPEED and once it reaches the edge of the screen, it will be marked as inactive, by setting its active variable to 0. Since we are moving from left to right, we need to check the position of the left edge of the sprite to prevent it from being made inactive prematurely.

Conclusion

Like the previous tutorial, firing a basic bullet is quite simple. In the next tutorial, we will look into collision detection.

Downloads

Source Code

Mobile site