How to make a PICO-8 game: Part 3

Chase me.

Last time, we got a square moving round the screen and accounted for bumping into the walls. This time, we’ll give old Squarey a reason to move around – something to chase him. Or her.

Part 3: Chase me

Right back at the start, we created an extra sprite to use as an enemy – Sprite 2. We’ll make use of that now.

Firstly, we need an initial position for our enemy. As we’re using x and y for the player, let’s use ex and ey for the enemy, and start it in the bottom right of the screen. 120, 120 perhaps. We’re also going to assign a speed to it – how far it moves each frame – and call it d (for distance, in pixels). We put these assignments in our _init() function:

We also need to display this enemy on the screen, so in the _draw() function, remembering the enemy sprite is in slot 2, we can use:

All this does so far, though, is show a square in the bottom right. We still need to make it move, and to do that we need to check where it is in relation to the player. In English, we want this:

“If the player is to the left of the enemy, move the enemy left”

“If the player is to the right of the enemy, move the enemy right”

That is, if x is less than ex then the player is to the left, and if x is greater than ex then the player is to the right. We can do the same for up and down with y and ey.

So how do we make it move left? Decrement ex. Right? Increment ex. Up? Decrement ey. Down? Increment ey. And how much do we increment or decrement by? Our variable d. Easy! Let’s do the if checks in _update(), after we’ve moved the player:

Now run the code, and watch how the enemy chases the player. Very, very slowly. Have a play with the value of d in the _init() function to see how this changes the speed of the enemy – try 0.1 or 1 instead of 0.05, for example.

Chase me!

Obviously, the game is very easy at this point, and not least because nothing happens if the enemy catches you. Why not? Because we’ve not coded any collisions yet! That’s what we’ll do next time. For now, here’s all the code so far, with some additional annotations so we’ll remember what everything does:

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

Leave a Reply