PICO-8: How do I shoot? Dynamic objects and tables

Shooting in Pico-8

PICO-8 is a small and sweet game engine aka fantasy console. This article explains how to add and remove objects like bullets to a game at playtime in PICO-8.

One question that I always get asked is: how do I add and remove multiple objects to a game dynamically. Stuff like projectiles, bullets or particles. No problem: I will show how to create objects on-the-fly in PICO-8.

BulletOne, BulletTwo, BulletThree, BulletFour

Probably the first idea is to make a new table for each object and saving it on a variable. We can just define a bunch of bullets and then set them when we press shoot.

local bulletOne = {
	x = 32, y = 32, 
	active = false, 
	draw = function(self)
		circfill(self.x, self.y, 7, 8)
	end
}

In our _draw callback we execute the draw() function of bulletOne: bulletOne:draw(). Making tables might be ok but having one variable for one object is very limiting. Is there a better way?

There must be a better way

Arrays can save you a lot of writing and duplicate code. Instead of using individual variables we can use a holding object.

bullets = {}
add(bullets, {
	x = 32, y = 32, 
	active = false, 
	draw = function(self)
		circfill(self.x, self.y, 7, 8)
	end
})

This way we can add as many objects to the bullets table as we like. And without creating a new variable every time.

Use PICO-8 iterators

How do we call the draw function for all the bullets in our _draw callback function? We use PICO-8 all() iterator function:

function _draw()
    for bullet in all(bullets) do
        bullet:draw()
    end
end

 

Additional: Global vs Local Variables

Global means that it can be accessed anywhere in your program. But there is also a table for the local scope. Local means that it is only accessible in the current part of your program. You can assign a variable to the local scope using the local keyword.

 

How to set up Vuforia and Unity

This is a getting started guide for augmented reality development. A short but complete tutorial on how to set up Vuforia with Unity 5.6.0f3 personal. In the end you will have a 3D cube on a marker.

  1. Create Account at Unity
  2. Download Unity 5.6.0f3
  3. Create Account at Vuforia
  4. Login into Vuforia.com and download the .unitypackage via Download for Unity
  5. Develop -> License Manager tab, select Add License Key
  6. Develop -> Target Manager
  7. Create new Database by clicking Add
  8. Make digital photo of marker or download this one
  9. Cut out marker in Photoshop/Paint
  10. Targetmanager > yournewdatabase > add target
  11. Upload marker image and click Add. Problems with upload? Use jpg and not png!
  12. Download Database, select Unity Editor > Download
  13. Create new project in unity
  14. Import the vuforia .unitypackage and the database .unitypackage by dragging it into project window
  15. Obsolete API warning: click go ahead and upgrade
  16. Toolbar window > Vuforia > Configuration > paste the App license key there
  17. Add your License Key and activate the datasets

    Toolbar window > Vuforia > Configuration > Datasets > load yournewdatabasename Database and click activate

  18. Project window > Assets > Vuforia > Prefabs > ARCamera add to scene
  19. Project window > Assets > Vuforia > Prefabs > ImageTarget add to scene
  20. Hierachy > Select ImageTarget
  21. Inspector > Find section Image Target Behaviour(Script)
  22. Inspector: set database to yournewdatabase and image target to marker
  23. Add a cube as the child of the ImageTarget gameobject
  24. Run and test your project

Optional next steps: you could add a script to the cube to make it rotate

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class rotate : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        transform.Rotate(Vector3.up*Time.deltaTime*100);
    }
}

Seven Fav Pico-8 Games

#7FavePico8Games
PICO-8_38
Ufo Tofu
http://www.lexaloffle.com/bbs/?tid=4055

 

PICO-8_36
Uhura
http://www.lexaloffle.com/bbs/?tid=3736

 

PICO-8_34
Matchy Matchy
http://www.lexaloffle.com/bbs/?tid=4022

 

PICO-8_37
Tea
http://www.lexaloffle.com/bbs/?tid=2829

 

PICO-8_39
Triotos-8
http://www.lexaloffle.com/bbs/?tid=3996

 

PICO-8_40
Nora’s Mouse Chase
http://www.lexaloffle.com/bbs/?tid=3414

 

PICO-8_41
P.Craft http://www.lexaloffle.com/bbs/?tid=3200

 

Not included anything by Benjamin Soule. His are all A+. Also check out Sophie Houldens game!

Arrays and Tables in Pico-8

2D Arrays

Screen Shot 2016-07-16 at 17.36.17

For beginners, I suggest you use concatenation to index 2D arrays. Create a new object in a 2D cell at (i,j) in a table called myArray with the following code:

myArray[i..","..j] = {}

To iterate over all objects in the myArray you can use the pairs iterator. Caution: the objects are not ordered when using pairs!

for k,v in pairs(myArray) do
	-- v is the cell object
	-- k is a string in the form of "i,j"
end

If we want to access the objects in a particular order we should use nested for loops:

for i=1, 8 do
	for j=1, 8 do
		local cell = myArray[i..","..j] 
		-- do stuff with the cell
	end
end

Objects And Container

PICO-8_5

Entities like the spaceship in this gif are objects. Containers for objects are special in Pico-8 because we have a couple of built-in functions to help us manage insertion and deletion. I strongly suggest to use add(), del() and all() for container and entity management.

Create and add an object to a table with add():

local entities = {}
local player = {
	x = 3,
	y = 3,
	sprite = 5
}
add(entities, player)

In your _update or _draw callbacks, you will most likely want to loop over all objects. You should use all() for that:

for entity in all(entities) do
	-- do stuff here
end

You can use del() to remove an object from the container even while iterating over the container:

for entity in all(entities) do
	del(entities, entity)
end

This only works with all() and del() together! This is great for games where you have dynamic objects such as bullets, effects or timed events that are added and removed dynamically.

I hope that these two hints help you to get started with the awesome Pico-8 engine. For advanced users, other methods might be more efficient. I recommend reading the Pico-8 Docs or the PIL for more information.

NanoFL under Mac OS X

NanoFL 3.0.5 currently only features a .exe binary for windows. The program itself is wrapped with XULRunner from Mozilla and that makes it easy to run natively on Mac OS X.

If you have a current Firefox there is no need to install XULRunner(which anyway seems deprecated). You can execute XULRunner apps with -app switch. Use Wine to install the game and then copy the installation folder somewhere accessible. In the terminal you then execute the following to start NanoFL.

/Applications/Firefox.app/Contents/MacOS/firefox -app 
/Users/headchant/Downloads/nanofl/application.ini

or more generic

/Applications/Firefox.app/Contents/MacOS/firefox -app /path/to/your/application.ini

Use no line breaks and edit the path to your installation of NanoFL.

This should start NanoFL inside a Firefox instance with almost all features as the windows version. Have fun! Screen Shot 2016-04-07 at 14.10.08

NanoFL and HiDPI

NanoFL is a minimalistic and free alternative to Animate CC (formerly Flash Professional). It publishes to Apaches Cordova or HTML5 with for example an CreateJS generator. While fiddling around with it I ran into the usual high resolution issues that always come up with HTML5: Blurry images and text.

Thankfully, there is an easy fix:

If you use the CreateJS just add a Scene class in the Document Properties Screen Shot 2016-04-07 at 13.36.14

If you hit publish a directory structure is created:

├── bin
│   └── library.js
├── gen
│   └── base.js
├── library
│   └── scene.xml
├── publish
│   ├── cordova
│   └── html
│       ├── bin
│       │   └── library.js
│       └── test.html
├── src
│   └── Game.js
├── test.html
└── test.nfl

Inside the src folder you will find a Game.js file with some boilerplate code. As suggested by Kevin Newman it is quite easy to change the canvas of CreateJS to use the HiDPI settings. We modify the code from his blog to fit our NanoFL environment into the init function of the Game prototype:

var canvas = document.getElementById("mainCanvas");
var stage = this.parent;
if (window.devicePixelRatio) {
    // grab the width and height from canvas
    var height = canvas.getAttribute('height');
    var width = canvas.getAttribute('width');
    // reset the canvas width and height with window.devicePixelRatio applied
    canvas.setAttribute('width', Math.round(width * window.devicePixelRatio));
    canvas.setAttribute('height', Math.round( height * window.devicePixelRatio));
    // force the canvas back to the original size using css
    canvas.style.width = width+"px";
    canvas.style.height = height+"px";
    // set CreateJS to render scaled
    stage.scaleX = stage.scaleY = window.devicePixelRatio;
}

Et voila, that’s it!

Burn The Boards – Background Information

Georg wrote a pretty interesting article about the development and background of the Burn The Boards project for Madewithunity: http://madewith.unity.com/stories/burn-boards-making-unpleasant-reality-immersive-gaming-experience-1.

I was involved in the creation of the project and was part of the design team for it. The problems of electronic waste and the associated health risks of workers are a topic that interest me greatly. If you want some insight into how that serious game was made check out the article.