How to make a PICO-8 game: Part 9


Sprites are all well and good, but if they animate they look so much better. Let’s head towards the end of this project by polishing it a bit.

Part 9: Animation

First up, we need to have some frames of animation for the enemy sprites. To make it a bit more logical on the sprite screen, I’ve moved the first frame from “slot” 2 to “slot” 17, then edited it and created three more frames of animation:

It’s nothing fancy, but you can change that if you like.

Now, when we create the enemy, we need to pass an extra parameter to the make_enemy() function – the total number of animation frames for the sprite. Of course we could hard code this into the enemy object, but lets assume we might want to reuse this function at another time for a range of objects each with a varying number of animation frames.

Currently, the function starts with this:

We’ll add “eframemax” to this:

and then set:

in the function itself. You’ll see why we had en.frame = 0 in there now!

Next, we need to add some code to change which sprite to use, changing it every so many ticks so it animates like a flickbook. We already have variables for ticks and ticksmax to help with this.

In English, what we need to achieve is this:

  1. Count up ticks each loop of the game.
  2. If the ticks hit ticksmax, then change the sprite to the next frame.
  3. Restart the ticks counter.
  4. If the sprite frame passes framemax, set it back to the first frame.
  5. Draw the sprite.

The sprite to draw will be the “base” sprite (i.e. the first sprite of the animation, in this case sprite 17) plus the number of the frame. So 17+0 = 17, then 17+1 = 18, etc. looping back to 17+0. Clear? Great. Here’s the code, which needs to go in the en.draw() function within the make_enemy() function:

Note that the spr() code has to change to add the frame number to the sprite number!

One last thing to make this work: You know those two calls to make_enemy()? One in _init() and one in _update()? Well, they both want to create enemies with sprite number 2. It’s 17 now, so we have to change that. Also, we have to include the new framemax parameter.

For the former, change it to:

The “3” is the framemax – there are 4 frames numbered 0, 1, 2, 3, remember! The call in _update() needs to change similarly:

Save it, run it, and watch!

You can play with the “animation speed” using a different final value for ticksmax (the final parameter in the make_enemy() call) instead of 4. Or add more frames, and increase framemax appropriately.

Next time, we’ll look at animating the player too, but until then, here’s all the code so far:


Leave a Reply