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

Android Games

DDDDD
Number Blocks
Match 3 Warriors

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 (Second Edition) (Battle for the Solar System, #1)

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 the Mitikas Empire's civil war than the Helios Confederation is willing to let on. Somewhere out there the Pandoran army is gathering, preparing to bring ruin to all the galaxy...

Click here to learn more and read an extract!

« Back to tutorial listing

— Making a 2D split screen game —
Part 3: Loading Zone(s)

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

Introduction

We can fly, we can shoot. What we need now is a place to do it all. Up until now, we've been doing these things in a dark void. Some sort of environment would be good. In this part, we're going to introduce just that, by loading the world data from a file, and drawing it. We'll also be able to interact with it, by flying into it and shooting bullets into it. Just like our models, our zones are constructed from triangles, and are loaded from files that detail the coordinates of all the points.

Extract the archive, run cmake CMakeLists.txt, followed by make, and then use ./versus03 to run the code. You will see a window open like the one above, with the player's ship located just below the middle of the screen. Use the same controls as before. Note how if you fly into the walls or central point you will bounce off them. Bullets that are fired will also accurately strike the walls and middle triangle. Once you're finished, close the window to exit.

Inspecting the code

Loading, drawing, and processing our world is extremely simple, as we'll see. At this point, there isn't very much to it, although things will get a bit more complicated later on. For now, we can get everything setup, and lay the foundations.

Starting with structs.h:


struct Entity
{
	// snipped

	void (*tick)(Entity *self);
	void (*draw)(Entity *self);
	void (*touch)(Entity *self, Entity *other);
	Entity *next;
};

The only thing we need to do here is to update the Entity struct, to add in the familiar `touch` function pointer. This will be invoked whenever something touches an entity, whether it be the environment (the world), a bullet, another player, an item, etc. This is very similar to the `touch` functions we've seen in the past.

Moving on now to world.c. This is where we're doing all our major world processing. There's a number of functions in this file, but nothing difficult to understand. Let's start with initWorld:


void initWorld(void)
{
	double r, g, b;

	memset(&head, 0, sizeof(Triangle));
	tail = &head;

	hsvToRGB(rand() % 360, 1, 0.55, &r, &g, &b);

	worldColor.r = r;
	worldColor.g = g;
	worldColor.b = b;
	worldColor.a = 255;
}

We're first setting up a linked list, to hold the list of Triangles that will make up our zone (as `head` and `tail`). We're also randomly choosing a colour with which to render our zone. We do this by choosing a random hue (0 - 360) and converting it into RGB. The hsvToRGB function can be found in util.c (it's a very common function, so we won't detail it here). With our RGB values determined, we set them into an SDL_Color called worldColor that we'll use later on.

With our init step complete, we can next look at the loadWorld function. Before we get to that, we should take a look at the format of the zone data file itself:

9
0 0 0 900 50 0
50 0 0 900 50 900
50 0 50 30 1600 0
1600 0 50 30 1600 30
1600 850 50 900 1600 900
1600 30 1540 30 1600 850
50 850 50 900 1600 850
1540 30 1540 850 1600 850
800 370 700 530 900 530

Much like the models file, our world data is very simple. The first line details the number of triangles in the file (one per line, so this number can also be seen as the number lines that follow). The triangle data itself is a series of x and y values, 6 per line, that make up the three points of our triangle. There is no colour data to be found, unlike the Models.

Now let's look at the loadWorld function itself:


void loadWorld(int zoneNum)
{
	int       i, numLines, n;
	Triangle *t;
	FILE     *fp;
	char      filename[MAX_FILENAME_LENGTH];

	sprintf(filename, "data/zones/%02d.dat", zoneNum);

	fp = openFile(filename);

	fscanf(fp, "%d", &numLines);

	for (i = 0; i < numLines; i++)
	{
		t = spawnTriangle();

		for (n = 0; n < 3; n++)
		{
			fscanf(fp, "%f %f ", &t->points[n].x, &t->points[n].y);
		}
	}

	fclose(fp);
}

The function accepts a parameter, zoneNum, that represents the number of the zone we want to load. This is used to construct the `filename`. We open the file, and scan the first line, to get the number of triangles stored (as numLines). We then loop through all the lines in the file, calling a function named spawnTriangle to create a Triangle (assigned to `t`). We then use another for-loop to read each triangle point (3 of them), and assign them to the `x` and `y` variables of said point.

That's it..! That's all we need to do to load our world data. As you can see, it's very simple, and just like loading models (except without the colour information).

Next up, we have drawWorld:


void drawWorld(void)
{
	int        n;
	SDL_Vertex v;
	Triangle  *t;

	n = 0;

	for (t = head.next; t != NULL; t = t->next)
	{
		for (n = 0; n < 3; n++)
		{
			memset(&v, 0, sizeof(SDL_Vertex));

			v.position = t->points[n];
			v.color = t->colors[n];

			drawVertex(&v);
		}
	}
}

It should be clear what's going on here, but I'll briefly detail. We're looping through all the Triangles in our linked list, setting the SDL_Vertex data (`v`) using each one, and passing that data to our drawVertex function.

We next come to spawnTriangle:


static Triangle *spawnTriangle(void)
{
	Triangle *t;

	t = malloc(sizeof(Triangle));
	memset(t, 0, sizeof(Triangle));
	tail->next = t;
	tail = t;

	t->colors[0] = t->colors[1] = t->colors[2] = worldColor;

	t->colors[0].r *= 0.85;
	t->colors[0].g *= 0.85;
	t->colors[0].b *= 0.85;

	return t;
}

As you'd expect, this function creates a Triangle and adds it to our linked list. One thing of note is that when we create the Triangle, we're assigning its colors to those of worldColor, that we randomly set in our initWorld step. What we're next doing is darkening the RGB values of the first point by 15%. This produces a very subtle gradient in our world, per triangle, to stop it from looking completely flat and boring..! One could remove these three lines to have a flat look, if they desired, without breaking anything.

Finally, we have getWorldTriangles:


Triangle *getWorldTriangles(void)
{
	return head.next;
}

This is a actually a temporary function we've made until we implement our spactial grid, later on. All it does is return the first Triangle in our linked list, so we can loop through them, for the purposes of collision detection. It will be removed in a later part.

That's world.c complete. We can now move on to seeing how we're handling collision detection and response. We need our players and bullets to interact with the world, rather than ignoring it. So, first over to player.c, where we've updated initPlayer:


void initPlayer(int x, int y)
{
	// snipped

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

We're assigning a `touch` function to our player entity. Next up, we have the actual `touch` function:


static void touch(Entity *self, Entity *other)
{
	bounce(self);
}

For now, nothing special. If the player touches anything, we'll call `bounce`, to make repel them in the opposite direction to where they were going.

That's all for player.c. Over next to entities.c, where we've updated doEntities:


void doEntities(void)
{
	Entity *e;

	for (e = zone.entityHead.next; e != NULL; e = e->next)
	{
		e->tick(e);

		if (e->touch != NULL)
		{
			touchWorld(e);
		}
	}
}

As well as calling an entity's `tick`, we're now testing if they have a `touch` function set, and are calling touchWorld, if so:


static void touchWorld(Entity *e)
{
	int       n;
	Triangle *t;

	for (t = getWorldTriangles(); t != NULL; t = t->next)
	{
		for (n = 0; n < 3; n++)
		{
			if (lineCircleCollision(t->points[n].x, t->points[n].y, t->points[(n + 1) % 3].x, t->points[(n + 1) % 3].y, e->position.x, e->position.y, e->radius))
			{
				e->touch(e, NULL);
				return;
			}
		}
	}
}

The summary of this function is that we're looping through all the triangles in our world (with the help of getWorldTriangles). We're then testing to see if the bounding sphere of our entity is intersecting any of the lines in our Triangle (our for-loop will test lines 0-1, 1-2, 2-0, in that order). We call a function named lineCircleCollision (in util.c) to check this. If the check resolves to true, we'll call the entity's `touch` function (passing over NULL right now).

Not complicated, at all. We're basically seeing if any of the lines of a given Triangle are intersecting our entity (via their bounding sphere). You're probably aware that this means that if our entity is placed directly inside a Triangle, without touching any lines, this test will fail. While true, I have never seen this happen to the player, even when their ship is moving extremely fast. We can therefore safely conclude that this check meet the needs of our game.

While trying this part out, you will likley have become aware of the fact that the player's ship is allowed to enter portions of the world, without issue. This is, again, due to the bounding circle having a radius smaller than the ship itself. This is to provide some leeway, and is quite a common compromise when handling collision checks. Further, you might be wonder why we're not checking if the entity's model's triangles are intersecting with the world's triangles? While this gives us a highly accurate collision check, that looks great, it has a huge downside - and that is that the player can become stuck in the world all too easily. Rotating around, for example, can cause our model's triangles to enter the world and prevent the player from then being able to move. A solution to this would be to perform various checks before applying the rotation (a near-full physics simulation). However, this now has gameplay issues, in that the player can drive themselves into a corner from which they cannot escape (unless we give them the ability to reverse). All in all, a fully accurate collision check for the player would become far too frustrating, and make our game less fun to play.

So, now you know. There's a method to the madness!

As for the line-circle check itself - this is some complicated maths that can found in a numerous forms and places (internet, books, your old trigonometry homework ...). I won't pretend to understand it all. For the curious, the function is listed below:


uint8_t lineCircleCollision(double x1, double y1, double x2, double y2, double cx, double cy, double r)
{
	double dx, dy, a, b, c, t;

	dx = x2 - x1;
	dy = y2 - y1;
	a = dx * dx + dy * dy;
	b = 2 * ((dx * (x1 - cx)) + (dy * (y1 - cy)));
	c = (cx - x1) * (cx - x1) + (cy - y1) * (cy - y1) - r * r;

	if (a == 0)
	{
		return c >= 0;
	}
	else
	{
		if (b * b - 4 * a * c < 0)
		{
			return 0;
		}

		t = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);

		if (t < 0 || t > 1)
		{
			return 0;
		}

		return 1;
	}
}

That's it for our entites. We can now deal with bullets interacting with the world. Starting with doBullets:


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

	prev = &head;

	for (b = head.next; b != NULL; b = b->next)
	{
		// snipped

		touchWorld(b);

		// snipped

		prev = b;
	}
}

For each bullet, we're now calling a new function named touchWorld, passing the bullet (`b`) over.

The touchWorld function is defined as such:


static void touchWorld(Bullet *b)
{
	Triangle *t;

	for (t = getWorldTriangles(); t != NULL; t = t->next)
	{
		if (pointInTriangle(b->position.x, b->position.y, t->points[0].x, t->points[0].y, t->points[1].x, t->points[1].y, t->points[2].x, t->points[2].y))
		{
			b->health = 0;
			return;
		}
	}

	if (!collision(b->position.x, b->position.y, b->radius, b->radius, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
	{
		b->health = 0;
	}
}

Once again, we're fetching all the world's Triangles, and looping through them. This time, however, we're testing if the bullet's center point (its origin) has entered into any triangles, using a function called pointInTriangle. This gets us a much nicer and accurate collision test than checking the radius against the world (and in this case, we don't need to worry about the bullet getting stuck). If the bullet has hit the world, we'll set its `health` to 0, and return from the function. This function also now tests if the bullet has moved outside of the screen (not that such a thing is possible in this demo zone), but it's here anyway..!).

For those interested, the pointInTriangle function can be found below:


uint8_t pointInTriangle(double px, double py, double x1, double y1, double x2, double y2, double x3, double y3)
{
	double lambda1, lambda2, lambda3;

	lambda1 = ((y2 - y3) * (px - x3) + (x3 - x2) * (py - y3)) / ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
	lambda2 = ((y3 - y1) * (px - x3) + (x1 - x3) * (py - y3)) / ((y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3));
	lambda3 = 1 - lambda1 - lambda2;

	return (lambda1 >= 0 && lambda1 <= 1 && lambda2 >= 0 && lambda2 <= 1 && lambda3 >= 0 && lambda3 <= 1);
}

That's our world loading and collision checks all done! We're almost done now, and just need to update zone.c with our new functions. Starting with initZone:


void initZone(void)
{
	memset(&zone, 0, sizeof(Zone));

	initEntities();

	initBullets();

	initWorld();

	loadWorld(0);

	initPlayer(SCREEN_WIDTH / 2, (SCREEN_HEIGHT / 2) + 300);

	app.delegate.logic = logic;
	app.delegate.draw = draw;
}

We're now calling initWorld and loadWorld (passing over 0, to make it load data/zones/00.dat).

Lastly, we've updated `draw`:


static void draw(void)
{
	drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 24, 255);

	drawWorld();

	drawEntities();

	drawBullets();
}

We're calling drawWorld here, doing so before drawEntities and drawBullets.

And that's that! We can load our world geometry and interact with it (and give it a random hue each time the game starts). Everything is progressing very nicely, and is extremely easy to work with.

But there's something missing, something very important that was the whole purpose of this tutorial set ... Isn't this meant to be a two-player game? And if so, where is the second player? Well, in our next part we'll be introducing the second player, who can be controlled with their own scheme (either keyboard or joystick). This is where things will start to get even more exciting!

Purchase

The source code for all parts of this tutorial (including assets) is available for purchase, as part of the SDL2 tutorials bundle:

From itch.io

Mobile site