How to make a PICO-8 game: Part 4

Crash! But not that sort of crash.

In Part 3, we made an enemy chase the player. Which was nice, but nothing actually happened when the player was caught. Why not? Because we had no code to check for collisions! Let’s fix that.

Part 4: Collision check

What is a collision? Well, for the purposes of our game – and most games – it’s when two objects overlap. In our case, it’ll be our player sprite and our enemy sprite. That’s pretty simple to understand, but how do we code it?

Let’s look at the definition in plain English. Both sprites are 8 pixels wide, and we need to check if any part of each sprite is “inside” the area of the other. Things will be different for different sized sprites, but let’s keep it simple for now.

The player sprite’s four corners are:

And the enemy sprite coordinates are:

So when they overlap, all of the following must be true (follow along with two squares of paper if that helps!):

  • The right edge of the enemy must be to the right of the left edge of the player (ex+8 > x), AND
  • The left edge of the enemy must be to the left of the right edge of the player (ex < x+8), AND
  • The bottom edge of the enemy must be below the top edge of the player (ey+8 < y), AND
  • The top edge of the enemy must be above the bottom edge of the player (ey > y+8)

In PICO-8, that translates to:

Let’s plan ahead a little, and assume we’re going to reuse the collision code for other things later on. After all, we might add more enemies, right? Let’s create a function to check collisions between two objects, using this code as the base. The function will return true if there’s a collision, and false if not:

Now we can send the coordinates of any two objects to that function and get a true or false in return. We’ll put a call to it in the _update() function (before we move anything), and stop the game if there’s a collision. Later, we can lose a life or something instead, but for now we’ll just stop().

Remember that “if checkcol(x,y,ex,ey) then” implies “if checkcol(x,y,ex,ey) == true”.

Here’s a catchup of all the code so far:

 

One thought on “How to make a PICO-8 game: Part 4”

Leave a Reply