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 Honour of the Knights (First Edition) (The Battle for the Solar System)

When starfighter pilot Simon Dodds is enrolled in a top secret military project, he and his wingmates begin to suspect that there is a lot more to the theft of a legendary battleship and an Imperial nation's civil war than either the Confederation Stellar Navy or the government are willing to let on.

Click here to learn more and read an extract!

« Back to tutorial listing

— Creating a vertical shoot 'em up —
Part 7: More power-ups

Note: this tutorial assumes knowledge of C, as well as prior tutorials.

Introduction

We've already got one power-up type: the sidearm. We also made promises in our code that we would offer more; the power-up pod can rotate between the offerings on a timer. In this part of the tutorial, we're going to add in those missing power-ups, including the ability for the player to increase their movement speed and rate of fire.

Extract the archive, run cmake CMakeLists.txt, followed by make, and then use ./shooter2-07 to run the code. You will see a window open like the one above. Use the arrow keys to move the fighter around, and the left control key to fire. Destroy the supply ships that appear at the top of the screen, to spawn a power-up pod. The pods can be shot to push them back up the screen, to allow time for them to change to something more desirable. When you're finished, close the window to exit.

Inspecting the code

To start with, we've expanded our defs.h enums to specify the new types:


enum {
	ET_PLAYER,
	ET_ALIEN,
	ET_POINTS,
	ET_SIDEARM,
	ET_DRONE,
	ET_POWER_UP_POD
};

We now have entity types (ET) for the sidearms (ET_SIDEARM) and drones (ET_DRONE). Note that these two enums replace the original ET_POWER_UP enum. We've done this so that we can more easily manage our power-ups, as we'll see later on. We've also added to our power-up pod types:


enum {
	PP_SIDEARM,
	PP_SHIELD,
	PP_DRONE,
	PP_SPEED,
	PP_RELOAD_RATE,
	PP_MAX
};

Again, we used to only have a power-up pod (PP_POWER_UP_POD) to represent a sidearm. Now, we support shield, drone, speed, and reload rate power-up pods.

structs.h has also been updated with the Drone struct:


typedef struct {
	double dx;
	double dy;
	double thinkTime;
	Entity *target;
	double attackTime;
	int numShotsToFire;
	double reload;
	double damageTimer;
} Drone;

Our Drone is an entity that moves randomly around the screen and attacks nearby enemies. Its fields will likely remind you of the bosses we created in the previous part. `dx` and `dy` will control the direction the Drone is moving. thinkTime will govern how long before the drone changes direction. `target` will be used to track the entity's current target, while attackTime, numShotsToFire, and `reload` will control its attacking phase. Note that damageTimer also exists. This is because our drone is not immortal or invulnerable, and can be hurt (and destroyed) by enemy fire. We also extended the same weakness to the regular sidearms:


typedef struct {
	int ox;
	double damageTimer;
} Sidearm;

Sidearms can now be hurt and destroyed by enemy fire, so the player will need to collect another power-up pod to replace them.

We'll now look at powerUp.c, where we've made a bunch of updates to support our new power-ups. Pretty much every function has been changed, so let's start with addPowerUpPod:


void addPowerUpPod(int x, int y)
{
	PowerUpPod *p;
	Entity *e;

	p = malloc(sizeof(PowerUpPod));
	memset(p, 0, sizeof(PowerUpPod));

	p->type = rand() % PP_MAX;
	p->changeTimer = CHANGE_TIMER;

	e = spawnEntity(ET_POWER_UP_POD);
	e->x = x;
	e->y = y;
	e->data = p;

	e->tick = tick;
	e->takeDamage = takeDamage;

	if (sidearmPodTexture == NULL)
	{
		sidearmPodTexture = getAtlasImage("gfx/sidearmPowerUpPod.png", 1);
		shieldPodTexture = getAtlasImage("gfx/shieldPowerUpPod.png", 1);
		dronePodTexture = getAtlasImage("gfx/dronePowerUpPod.png", 1);
		speedPodTexture = getAtlasImage("gfx/speedPowerUpPod.png", 1);
		reloadRatePodTexture = getAtlasImage("gfx/reloadRatePowerUpPod.png", 1);
	}

	updateTexture(e, p);
}

The first change is that we're now assigning a takeDamage function to the power-up pod's entity. Next, we're loading a total of 5 textures, to represent our power-up pods. sidearmPodTexture, shieldPodTexture, dronePodTexture, speedPodTexture, and reloadRatePodTexture all represent their given types (should be clear what they represent..!). One thing you might have noticed is that the blue power-up pod now provides the shield, and not the sidearms, as before. I felt that since the shield is blue, it would make more sense for the blue power-up pod to do this. Red is also seen to represent danger, and so having this for the sidearms works out nicely.

Next, we have the takeDamage function. It's very simple:


static void takeDamage(Entity *self, int amount)
{
	self->y -= self->texture->rect.h;
}

When the PowerUpPod is hit by a bullet, we will substract the value of its texture's height from it's `y` coordinate, effectively pushing it back up the screen. This is something that can be used by the player to wait for the pod to change into something more desirable before collecting it.

We've also updated updateTexture to accomodate the new textures:


static void updateTexture(Entity *e, PowerUpPod *p)
{
	switch (p->type)
	{
		case PP_SIDEARM:
			e->texture = sidearmPodTexture;
			break;

		case PP_SHIELD:
			e->texture = shieldPodTexture;
			break;

		case PP_DRONE:
			e->texture = dronePodTexture;
			break;

		case PP_SPEED:
			e->texture = speedPodTexture;
			break;

		case PP_RELOAD_RATE:
			e->texture = reloadRatePodTexture;
			break;

		default:
			break;
	}
}

There's not much to say about the updates to this function, as it should be quite clear what's going on - we're just assigning the entity's texture according to the PowerUpPod's type.

Now we come to the activatePowerUp function, which is where the logic for handling all our new power-ups comes into play:


static void activatePowerUp(Entity *self, PowerUpPod *p)
{
	Fighter *f;

	switch (p->type)
	{
		case PP_SIDEARM:
			removeSideArms();
			initSidearm(-48);
			initSidearm(48);
			break;

		case PP_SHIELD:
			player->health = 5;
			break;

		case PP_DRONE:
			if (canSpawnDrone())
			{
				initDrone();
			}
			break;

		case PP_SPEED:
			f = (Fighter*) player->data;
			f->speed = MIN(f->speed + 2, MAX_FIGHTER_SPEED);
			break;

		case PP_RELOAD_RATE:
			f = (Fighter*) player->data;
			f->reloadRate = MAX(f->reloadRate - 4, MAX_FIGHTER_RELOAD_RATE);
			break;

		default:
			break;
	}

	self->health = 0;
}

We're checking what type of PowerUpPod we've interacted with and responding accordingly. If we've touched a sidearm power-up (PP_SIDEARM), we're granting the player some sidearms. Note, however, that we're first removing the existing sidearms. This is something we didn't do in the previous tutorials, meaning our firepower could increase hugely. We therefore want to limit this. We'll see what this function does in a bit. Next, we're handling the shield power-up. All this power-up does is set the player's health to 5, allowing them to take 5 hits before they are killed. For a PP_DRONE type power-up, we're testing to see if we can create a drone before calling initDrone. This is to limit the number of Drones the player can have assisting them, so that we don't reach some absurd number.

Like the PP_SHIELD type, the PP_SPEED and PP_RELOAD_RATE power-up pods affect the player directly, or rather the Fighter. You might remember that we added fields to the player's Fighter for their speed and rate of fire, rather than use constants. We finally get to see these being put to more effective use. When touching a PP_SPEED power-up, we extract the Fighter from the player's `data` field and increase its speed by 2. We limit the speed to MAX_FIGHTER_SPEED (defined in defs.h as 12). For PP_RELOAD_RATE, we're decreasing the Fighter's reloadRate by 4, again limiting it to MAX_FIGHTER_RELOAD_RATE (defined as 4). These allow the player to move very fast and fire very quickly.

We'll look next at two functions that are called by activatePowerUp, starting with removeSideArms:


static void removeSideArms(void)
{
	Entity *e;

	for (e = stage.entityHead.next ; e != NULL ; e = e->next)
	{
		if (e->type == ET_SIDEARM)
		{
			e->health = 0;
		}
	}
}

All this function does is loop through all the entities active in the Stage, looking for any ET_SIDEARM types. If we find one, we'll set its `health` to 0, thereby removing it. Now, this might seem a bit heavy-handed, but the alternative to dealing with updating the sidearms would involve a bit of micromanagement, to find how many sidearms need to be added and in which position. Removing and re-adding them is the best solution here.

The other function, canSpawnDrone, isn't too different:


static int canSpawnDrone(void)
{
	int n;
	Entity *e;

	n = 0;

	for (e = stage.entityHead.next ; e != NULL ; e = e->next)
	{
		if (e->type == ET_DRONE)
		{
			n++;
		}
	}

	return n < MAX_DRONES;
}

We're looping through all the active entities and counting how many Drones there are. The function will then return 1 or 0 (true or false) depending on whether there are fewer than MAX_DRONES (defined as 3). In effect, if we already have 3 Drones active, the power-up will do nothing.

Let's now look at how our Drone works. All his functions are defined in drone.c, and there's a good number of them. We'll start with initDrone:


void initDrone(void)
{
	Drone *d;
	Entity *e;

	d = malloc(sizeof(Drone));
	memset(d, 0, sizeof(Drone));

	if (droneTexture == NULL)
	{
		droneTexture = getAtlasImage("gfx/drone.png", 1);
		bulletTexture = getAtlasImage("gfx/droneBullet.png", 1);
	}

	e = spawnEntity(ET_DRONE);
	e->health = 3;
	e->texture = droneTexture;
	e->data = d;

	e->x = player->x + (player->texture->rect.w / 2) - (droneTexture->rect.w / 2);
	e->y = player->y + player->texture->rect.h;

	e->tick = tick;
	e->draw = draw;
	e->takeDamage = takeDamage;
}

We're mallocing and memsetting a Drone, then fetching the required textures. Our drone will be using a different bullet from the player, since it can move in any direction. Like some of the bosses, the Drone's bullet is a sphere (but blue in colour). With that done, we spawn our Entity with a type of ET_DRONE. Note that the drone has 3 health points, allowing it to be shot three times before it is killed. The drone's `texture` and `data` fields are set, and then we're positioning the drone to the middle bottom of the player. Finally, the `tick`, `draw`, and takeDamage functions are assigned.

Just like the bosses, the `tick` function for the Drone is quite meaty, as it's where its behaviour is performed:


static void tick(Entity *self)
{
	Drone *d;

	d = (Drone*) self->data;

	self->x += d->dx;
	self->x = MAX(MIN(self->x, SCREEN_WIDTH - self->texture->rect.w), 0);

	self->y += d->dy;
	self->y = MAX(MIN(self->y, SCREEN_HEIGHT - self->texture->rect.h), 0);

	d->thinkTime = MAX(d->thinkTime - app.deltaTime, 0);

	if (d->thinkTime == 0)
	{
		d->dx = d->dy = 0;

		if (rand() % 3 != 0)
		{
			d->dx = (1.0 * (rand() % 500 - rand() % 500)) * 0.001;
			d->dy = (1.0 * (rand() % 500 - rand() % 500)) * 0.001;
		}

		d->thinkTime = FPS * (25 + (rand() % 75));
		d->thinkTime *= 0.01;
	}

	d->attackTime = MAX(d->attackTime - app.deltaTime, 0);

	if (d->attackTime == 0)
	{
		if (d->target == NULL || d->target->health <= 0)
		{
			selectTarget(self);
		}

		if (d->target != NULL)
		{
			d->numShotsToFire = 1 + rand() % 3;
		}

		d->attackTime = FPS * (2 + (rand() % 4));
	}

	d->reload = MAX(d->reload - app.deltaTime, 0);

	if (d->reload == 0 && d->numShotsToFire > 0)
	{
		d->numShotsToFire--;

		d->reload = 12;

		fireBullets(self);
	}

	if (player->health <= 0)
	{
		addExplosion(self->x + (self->texture->rect.w / 2), self->y + (self->texture->rect.h / 2));

		self->health = 0;
	}

	d->damageTimer = MAX(d->damageTimer - app.deltaTime, 0);
}

As I said, there's a lot! Starting from the top: the first thing we're doing is extracting the Drone from the entity `data` field. We're then moving the Drone according to its `dx` and `dy` values, by adding them to the entity's `x` and `y`. We're also constraining the Drone to the screen, via some MAX and MIN macros. Much like the player, the Drone's `x` and `y` values won't be allowed to go lower than 0, and not higher SCREEN_WIDTH and SCREEN_HEIGHT on the x and y.

We're then decreasing the thinkTime and limiting it to 0. If we hit 0, we'll want to update the Drone's movement. We're first telling it to hold position, by setting its `dx` and `dy` to 0. There's then a 2 in 3 chance that we'll update the `dx` and `dy` values to something random, making the drone move about. With that done, we're resetting the thinkTime to something random, to let the drone continue on its path for a while, much like how we do with the bosses.

attackTime comes next. Once again, we're decreasing the value and limiting it to 0. Once it reaches 0, the Drone will be ready to attack. Here's where things get interesting, as the Drone doesn't just fire straight up the screen, it actively looks for a target. We're first testing if the Drone has a target or if its current target's health is 0 or less. If so, we're calling a function called selectTarget (which we'll look at in a bit). Should that call result in the Drone finding a target to attack, it will choose to fire between 1 and 3 shots, before resetting its attackTime to between 2 and 5 seconds.

Following this, we're going to check if the Drone is able to fire at its target. We're decreasing the Drone's `reload` and limiting it to 0, then testing if the `reload` is 0 and that numShotsToFire is greater than 0. If so, we're decreasing the numShotsToFire, resetting the `reload`, and calling fireBullets (we'll see this in a bit).

Finally, we're testing if the player has been killed. If so, the Drone itself will die, adding an explosion at its position and setting its own `health` to 0. We're also decreasing the Drone's damageTimer, and limiting it to 0.

All in all, we can see that the Drone move around the screen randomly, firing at enemies. It doesn't do so too often, but keep in mind the player can have up to 3 Drones assisting, meaning that they have the advantage of numbers.

Now, let's look at what selectTarget does:


static void selectTarget(Entity *self)
{
	Entity *e;
	double dist, bestDist;
	Drone *d;

	d = (Drone*) self->data;

	d->target = NULL;

	for (e = stage.entityHead.next ; e != NULL ; e = e->next)
	{
		if (e->type == ET_ALIEN)
		{
			dist = getDistance(self->x, self->y, e->x, e->y);

			if (d->target == NULL || dist < bestDist)
			{
				d->target = e;

				bestDist = dist;
			}
		}
	}
}

After extracting the Drone data from our entity, we're setting the Drone's `target` to NULL, to force it to not have a target. Next, we're looping through all the entities in the Stage, looking for aliens. If we encounter one, we're calculating the distance between it and the Drone, by calling a function called getDistance, and feeding in the Drone's position and the alien's position. We're assigning the value of this calculation to a variable called `dist`. The alien will become the target of the Drone if the Drone doesn't already have a target or if alien is closer to the Drone than the best distance (`bestDist`). If the alien does become the target of the Drone, the value of `bestDist` will be updated to the value of `dist`, meaning that only an alien that is now closer to the Drone than the current target will become the new one.

In summary, the Drone will select the nearest alien to it as it's target.

In case you're wondering what the getDistance function looks like, it can be found in util.c:


int getDistance(int x1, int y1, int x2, int y2)
{
	int x, y;

	x = x2 - x1;
	y = y2 - y1;

	return sqrt(x * x + y * y);
}

Just a standard distance function. Simple, but highly useful (and quite portable).

We should cover the remaining functions now, though they won't come as a shock. Starting with `draw`:


static void draw(Entity *self)
{
	Drone *d;

	d = (Drone*) self->data;

	if (d->damageTimer == 0)
	{
		blitAtlasImage(self->texture, self->x, self->y, 0, SDL_FLIP_NONE);
	}
	else
	{
		SDL_SetTextureColorMod(self->texture->texture, 255, 32, 32);
		blitAtlasImage(self->texture, self->x, self->y, 0, SDL_FLIP_NONE);
		SDL_SetTextureColorMod(self->texture->texture, 255, 255, 255);
	}
}

We're testing the Drone's damageTimer to see how we want to draw the drone. If it's 0, we'll draw the Drone as normal. However, if it's not we know that the Drone has taken damage. We'll draw the Drone with a red tint applied (using SDL_SetTextureColorMod and feeding in the entire texture atlas). Using the blending modifier as we do with the aliens doesn't work so well for the Drone, due to its colours, so drawing it in red helps. We're then changing the texture atlas's colours back to white (255, 255, 255) after we're done, so everything else doesn't render in red..!

As stated earlier, the Drone is vulnerable to attacks from aliens bullets, so it has its own takeDamage function:


static void takeDamage(Entity *self, int amount)
{
	self->health -= amount;

	if (self->health <= 0)
	{
		die(self);
	}

	((Drone*) self->data)->damageTimer = 8;
}

Nothing unexpected. We reduce the Drone's `health` by the value of `amount`. If it falls to 0 or less, we'll call the `die` function. We'll also set the Drone's damageTimer to 8, to show it has taken a hit.

There's very little to the `die` function:


static void die(Entity *self)
{
	addExplosion(self->x + (self->texture->rect.w / 2), self->y + (self->texture->rect.h / 2));
}

Just an explosion created with addExplosion, nothing more. The fireBullets function is a little more exciting:


static void fireBullets(Entity *self)
{
	Bullet *b;
	Drone *d;

	d = (Drone*) self->data;

	b = spawnBullet(player);
	b->texture = bulletTexture;
	b->x = self->x + (self->texture->rect.w / 2) - (bulletTexture->rect.w / 2);
	b->y = self->y + (self->texture->rect.h / 2) - (bulletTexture->rect.h / 2);

	calcSlope(d->target->x + (d->target->texture->rect.w / 2), d->target->y + (d->target->texture->rect.h / 2), b->x, b->y, &b->dx, &b->dy);

	b->dx *= 12;
	b->dy *= 12;
}

Just like the Blue Boss, the Drone fires a shot directed at its `target`. Worth noting is that when we spawn the bullet, it belongs to the player, not the Drone, just like with the sidearms. We set the bullet's texture and align it in the middle of the Drone. After that, we'll call calcSlope and feed in the midpoints of the target's `x` and `y` coordinates, the bullet's `x` and `y`, and also references to its `dx` and `dy`. With our velocity calculated, we just multiply up the `dx` and `dy` by 12, to make the bullet move fast towards the target.

That's our Drone concluded. As you can see, some of its behaviour is quite similar to that of the bosses. It's not the smartest companion, but as a mobile gun, it works well enough. Since our power-ups can now be damaged, we should see how we've updated our bullets to conform to this:


void doBullets(void)
{
	Bullet *b, *prev;

	prev = &stage.bulletHead;

	for (b = stage.bulletHead.next ; b != NULL ; b = b->next)
	{
		b->x += b->dx * app.deltaTime;
		b->y += b->dy * app.deltaTime;

		if (!collision(b->x, b->y, b->texture->rect.w, b->texture->rect.h, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
		{
			b->dead = 1;
		}
		else
		{
			doCollisions(b);
		}

		if (b->dead)
		{
			prev->next = b->next;

			if (b == stage.bulletTail)
			{
				stage.bulletTail = prev;
			}

			free(b);

			b = prev;
		}

		prev = b;
	}
}

While looping through our bullets, we've remove the functions that specifically handle the aliens or player, and now just have one function called doCollisons, which takes a bullet as a parameter:


static void doCollisions(Bullet *b)
{
	Entity *e;
	int checkHit;

	for (e = stage.entityHead.next ; e != NULL ; e = e->next)
	{
		checkHit = 0;

		switch (b->owner->type)
		{
			case ET_PLAYER:
				checkHit = e->type == ET_ALIEN || e->type == ET_POWER_UP_POD;
				break;

			case ET_ALIEN:
				checkHit = e->type == ET_PLAYER || e->type == ET_SIDEARM || e->type == ET_DRONE;
				break;

			default:
				break;
		}

		if (checkHit && collision(e->x, e->y, e->texture->rect.w, e->texture->rect.h, b->x, b->y, b->texture->rect.w, b->texture->rect.h))
		{
			e->takeDamage(e, 1);

			b->dead = 1;

			addSmallExplosion(b->x + (b->texture->rect.w / 2), b->y + (b->texture->rect.h / 2));
		}
	}
}

For each bullet, the function will loop through all the entities in the stage. We'll set a flag called checkHit to 0 (false) and then test the bullet owner's `type`. If it's ET_PLAYER and the entity we're currently checking is an alien (ET_ALIEN) or a power-up pod (ET_POWER_UP_POD), we'll set our checkHit flag to 1. Otherwise it will become false. If the owner type is an alien (ET_ALIEN) and the current entity is the player (ET_PLAYER), a sidearm (ET_SIDEARM), or a drone (ET_DRONE), we'll set checkHit to 1.

We then test the state of the checkHit flag. If it's 1 and a collision has taken place, we'll call the entity's takeDamage function. This means that we're now expecting a takeDamage function to have been set for an entity that a bullet can collide with. Be aware that we're not testing if it's NULL, which means if we don't set the function pointer, the game will crash when it tries to invoke the function pointer.

Again, it's somewhat wasteful to check every entity for each bullet. If our game was larger, we'd want to break things down a bit, to make them more manageable. With what we have right now, it's not too much of a concern. In a later tutorial, we'll look at dividing up the playfield, to reduce the number of collision checks.

As our sidearms are now vulnerable to enemy damage, we should look at what changes we made to enable this. We'll turn to sidearms.c and start with initSidearm:


void initSidearm(int ox)
{
	Sidearm *s;
	Entity *e;

	s = malloc(sizeof(Sidearm));
	memset(s, 0, sizeof(Sidearm));

	s->ox = ox;

	if (sidearmTexture == NULL)
	{
		sidearmTexture = getAtlasImage("gfx/sidearm.png", 1);
		bulletTexture = getAtlasImage("gfx/playerBullet.png", 1);
	}

	e = spawnEntity(ET_SIDEARM);
	e->health = 3;
	e->texture = sidearmTexture;
	e->data = s;

	e->tick = tick;
	e->draw = draw;
	e->takeDamage = takeDamage;
	e->die = die;

	tick(e);
}

The two changes here we've made is to give the sidearm's `health` a value of 3, allowing it to survive 3 hits before it is destroyed. We've also assigned `draw`, takeDamage, and `die` function pointers. Our `tick` has had a one line update, too:


static void tick(Entity *self)
{
	// snipped

	s->damageTimer = MAX(s->damageTimer - app.deltaTime, 0);
}

As the SideArm struct now has a damageTimer, we're decrementing it in the `tick` function, limiting it to 0. As expected, the damageTimer field comes into play in the draw function:


static void draw(Entity *self)
{
	Sidearm *s;

	s = (Sidearm*) self->data;

	if (s->damageTimer == 0)
	{
		blitAtlasImage(self->texture, self->x, self->y, 0, SDL_FLIP_NONE);
	}
	else
	{
		SDL_SetTextureColorMod(self->texture->texture, 255, 32, 32);
		blitAtlasImage(self->texture, self->x, self->y, 0, SDL_FLIP_NONE);
		SDL_SetTextureColorMod(self->texture->texture, 255, 255, 255);
	}
}

You'll recognise what's going on here as being the same as the `draw` function for the Drone. As with the Drone, we're drawing the sidearm in red when it is damaged, due to it being easier to recognise.

The sidearm's takeDamage function is also very familiar:


static void takeDamage(Entity *self, int amount)
{
	self->health -= amount;

	if (self->health <= 0)
	{
		die(self);
	}

	((Sidearm*) self->data)->damageTimer = 8;
}

A standard takeDamage function, that reduces the entity's `health` by `amount` and kills the sidearm as needed.

The last thing we've tweaked is the player. With the aid of a power-up, the player can now survive more than 1 hit, so we've made some tweaks to initPlayer:


void initPlayer(void)
{
	Fighter *f;

	f = malloc(sizeof(Fighter));
	memset(f, 0, sizeof(Fighter));

	f->speed = 4.0;
	f->reloadRate = 16;

	player = spawnEntity(ET_PLAYER);
	player->texture = getAtlasImage("gfx/player.png", 1);
	player->x = (SCREEN_WIDTH - player->texture->rect.w) / 2;
	player->y = SCREEN_HEIGHT - 100;
	player->data = f;

	player->tick = doPlayer;
	player->draw = draw;
	player->takeDamage = takeDamage;
	player->die = die;

	bulletTexture = getAtlasImage("gfx/playerBullet.png", 1);
	shieldTexture = getAtlasImage("gfx/shield.png", 1);
}

We're assigning two new function pointers to the player: `draw` and takeDamage. We're also grabbing a new texture for the shield effect, and assigning it to a variable called shieldTexture.

The takeDamage function we've created for the player is nothing special:


static void takeDamage(Entity *self, int amount)
{
	self->health -= amount;

	if (self->health <= 0)
	{
		self->die(self);
	}
}

We're just doing as we always do, which is to reduce the player's `health` by the amount specified, and kill them if `health` falls to 0 or less. This is, however, different from when we used to kill the player immediately in bullets.c.

Lastly, let's look at the `draw` function:


static void draw(Entity *self)
{
	int x, y;

	if (self->health > 1)
	{
		x = (self->x + (self->texture->rect.w / 2)) - (shieldTexture->rect.w / 2);
		y = (self->y + (self->texture->rect.h / 2)) - (shieldTexture->rect.h / 2);

		SDL_SetTextureAlphaMod(self->texture->texture, 50 * self->health);
		blitAtlasImage(shieldTexture, x, y, 0, SDL_FLIP_NONE);
		SDL_SetTextureAlphaMod(self->texture->texture, 255);
	}

	blitAtlasImage(self->texture, self->x, self->y, 0, SDL_FLIP_NONE);
}

There's a little more going on here than just drawing the player. You'll have noticed if you've grabbed the shield power-up that a blue sphere surrounds the player. We're handling this in the draw function. To begin with, we're testing if the player's `health` is greater than 1. If so, the player has a shield. We're first calculating the position of the shield by taking the center point of the player and the shield texture. We're then setting the shield texture's alpha (really the texture atlas's alpha) based on the amount of `health` the player has, multipled by 50. If the player has 5 `health`, the alpha will be 250. If the player has 4 health, it will be 200, and so on. This means that as the player takes damage and their `health` decreases, the alpha will also decrease, causing the shield to fade until it vanishes altogether.

We now have all our power-ups! There's just a few things left to finish off our game. We'll be introducing a couple more alien attack patterns, then layering on all the finishing touches, including a title screen, highscore table, sound effects, and music!

Purchase

The source code for all parts of this tutorial (including assets) is available for purchase:

From itch.io

It is also available as part of the SDL2 tutorial bundle:

Mobile site