Creators: Shootah Part 5 – Edges


This week we extended our colliders so that we could used them to prevent the player going off the edges of the screen. We used it to show how software design needs to evolve.


Our colliders were designed to be connected to an object with three things:

  1. A property  containing the x-coordinate of its location
  2. A property y containing the y-coordinate of its location
  3. A function hit() which was called if the attached collider touched another collider

Something to Connect To

We had colliders already attached to our:

  1. Enemy
  2. Bullets

but we didn’t have anything to attach to that could represent the side of the screen.

We created a new class called Static() with nothing more than the x, y  and hit() that we needed so that we could connect a collider to it (stored in one more property – collider).

Screen Edges

We created a pair of these colliders positioned at the right and left-hand side of the screen. We made sure to add them to our list in check_colliders(). Nothing much happened. Why? Well, first, the Player didn’t have a collider, so we added one, liberally copying code from Enemy, which a minor change to the description argument.

Now we could see the contact occurring between the edge and the player, though nothing was stopping it moving yet.

Unintended Consequences

As  often happens with code, this change had unexpected consequences; bullets were not firing properly any more. Why? Because the player now had a collider and the bullets were becoming inactive immediately because they were hitting that. The fix was to modify the Bullet’s hit() function to ignore hitting a collider with the description “player”.

Stopping the Player Moving

We now knew our player was hitting an edge, but another problem became apparent: we didn’t know which edge!

To properly stop the player and stop it moving too far, we really needed to know which side of the player the collider we’d hit was, but that information wasn’t available to us with the current design.

A couple of quick changes were necessary:

  1. In Collider.touching(), instead of just passing the descriptors to the objects hit() functions, we changed it to pass the Collider itself.
  2. In all the hit() functions, we had to made a small adjustment to account for the fact that we were now getting a Collider and not just a string.

With the extra information from the collider, were were able to determine how far the player should be allowed to move to and prevent it going further by setting the x value appropriately.


The files for this week can be found on our GitHub repository.

Creators: Shootah Part 4 – Colliders


This week we mainly dealt with building and using a box collider in our game. The box colliders are written in a way such that:

  • They are connected to something in the game and follow it around
    • What they are attached to must have the properties x and y for position
  • It is possible to test if they are touching each other
  • If two colliders are found to be touching, we tell the things that they’re attached to that they’ve been hit by something
    • What they are attached to must have a function hit() that we can call


Extents of the Collider

Our collider is a box, of a given width and height, centred on the x and y of the thing it’s connected to:

Untitled Diagram

For checking collisions, we need to know the values of the left and right side of the box and the y values of the top and the bottom of the box.

For convenience, we write a function which returns an object (using curly brackets) with the left, righttop, and bottom values (shortened lr, t and b respectively) as properties:

  return {
    l: this.connected.x - this.width / 2,
    r: this.connected.x + this.width / 2,
    t: this.connected.y - this.height / 2,
    b: this.connected.y + this.height / 2

When making an object like this, we set a property value by first writing the property name, followed by a  colon (:)  and then a space and the value we want it to have. Each property is separated with a comma. The don’t need to be on separate lines, but it makes it easier to read.


Touching Colliders

So how do we know that two colliders are touching? Actually there are four ways in which they definitely can’t be touching:

  • One is completely to the left of the other
  • One is completely to the right of the other
  • One is completely above the other
  • One is completely below the other

And if none of these are true, then it must be touching. So actually, we’re going to check that they’re not NOT touching (double negative, used correctly!).

How do we know if something is completely to the left of something else? Look at this diagram:


Untitled Diagram (1)

We know that box 2 (in blue) is totally to the left of box 1 (in orange) because we can see it is, but how could get the computer to check it? Remember, left and right are just x values on the screen. Box 2 is left of box 1 because both it’s left and right values are smaller than the left value of box 1.

The checks for the other directions are very similar:

  • The second box is right of the first box when both of it’s x values (left and right) are greater than the first’s right side.
  • The second box is above of the first box when both of it’s y values (top and bottom) are less than the first’s top side.
  • The second box is below of the first box when both of it’s y values (top and bottom) are greater than the first’s bottom side.


Sending Messages

Each collider has a property disc that describes the thing, or type of thing, that it’s connected to.

All colliders know what they’re connected to, so when we determine two have touched, we call a function called hit() on each of the connected objects, passing it the desc of the other collider. This means, in our game, when our enemy is hit, it can know that it’s been hit by a bullet – or maybe something else – and react appropriately.


Checking Every Collider Against Every Other

In our code, we gather all the active colliders at each frame. We then need to check each one against each every other one. How can we do that?

Consider a list of four items:

Untitled Diagram (2)

To check them all against each other we first need to check 0 against the other three. Simple enough.

We we need to check 1. But we don’t need to check 1 against 0, since we already did that. Nor do we need to check it against itself. We only need to check it against 2 and 3.

If we write out the full sequence, we see that for four items we need three passes to check all combinations:

  • First pass: Check 0-1, 0-2, 0-3
  • Second pass: Check 1-2, 1-3
  • Third pass: Check 2-3

We can write a pair of loops to do this:

for (let i = 0; i < c.length - 1; i++){
  for (let j = i + 1; j < c.length; j++){

Note two things about these loops:

  • The first loop goes from zero, but stops one short of the last item in the list (i < c.length – 1). It picks the first item to be checked.
  • The second loop doesn’t start from zero. It starts from what ever i currently is, plus one. It picks the second item to be checked.


Other Stuff

We also did a few other things this week:

  1. We fixed a small bug that was keeping our spaceship moving when we didn’t want it.
  2. We added a little drag to slow the spaceship down to a stop when we lift our fingers off the keys
  3. We set bullets inactive when they hit something



The files for this week can be found on our GitHub repository.

Creators – Shootah Part 3 – Enemies etc.

This week we continued our Shootah project. We did two main things;

  1. Changed the code to control the total number of bullets to those actually on screen
  2. Added an enemy that loops backwards and forwards across the screen

Controlling the Number of Bullets

In Part 2, we made a new bullet every time the user pressed the Up key and put it in the bullets list.

This meant that after a while we could have a lot of bullets, most off the top of the screen, which was even slowing some machines down.

To limit the number of bullets we did four things:

  1. Added a new property to the Bullet class called active and set it to be true
  2. In the move() function for the bullet class, we added a check for the bullet going off the top of the screen (this.y < 0) and, if true, set the active property to false
  3. In sketch.js, we moved the lines of code in the draw() function responsible for moving and drawing the bullets into a new function called manageBullets() and called it from draw().
  4. In manageBullets() we made a new list called active and put every bullet that was still active into it. We then made this the new bullets list.

We write a little code that printed out the total number of bullets to verify this was working.

Adding an Enemy

We added a new file called enemy.js and included it in the index.html file.

This file looked a lot like player.js. The main different was the move() function. Our enemy moves constantly left-to-right. When it gets too far off the right-hand side of the screen (checked in move()) we set its x position to be off the left-hand side of the screen instead. This makes it loop around.


We still have loads to do and we made a list on the day:

  • No more infinite bullets!
  • Check edges so spaceship doesn’t disappear
  • Enemies
  • Collision detection
  • Enemies shoot back (bombs)
  • Lives/score
  • Levels
  • Background music
  • Moving background
  • Story

We’ve done two and we’ll do some of the others for sure.


The files for this week can be found on our GitHub repository.


Creators – Painting


This week we looked at making a painting program.

We started with three built in P5.js variables:

  • mouseIsPressed – true whenever the mouse button is held down
  • mouseX – contains the X position of the mouse pointer
  • mouseY – contains the Y position of the mouse pointer

We put the call to background() in the setup() function because we didn’t want to clear the background every frame. After that, in the draw() function, we just needed to draw an circle at the mouse’s position every time the mouse button was pressed.

This gave us an very basic painting program in just a few lines of code!


We then looked at the idea of a toolbar to contain buttons for selecting colours and the size of the brush.

We first need to decide where it would be (the left side of the screen) and we created a variable toolbarSize to store the width of it.

In the draw() function we then added a check not to draw an circle if we were inside the toolbar area.

We then added a new function called mouseClicked(). This is a special function name (like setup() and draw()) that P5.js will call at the appropriate time. In this case its called when the mouse is clicked (button pressed down and the released).

Colour and Sizes

We created two arrays to store a list of colours and brush sizes at the top of our script:

let colours = ['black', 'white', 'red', 'blue', 'green'];
let sizes = [5, 10, 20, 40, 80, 160];

To draw the toolbar, we made a new function called drawToolbar() and put a call to it in our draw() function. In the new function, we looped over the colours array, drawing a new button, filled with the respective colour and then another loop over sizes drawing a square with a circle inside to represent the brush size. We needed to scale those circles to make them fit inside our buttons.

Detecting Selected Button

Since everything in our toolbar was toolbarSize high, to determine what had been clicked on, we just needed to divide mouseY by toolbarSize to get the index of the button that had been clicked on. We looked at that index, if it was less than the number of colours, we must have clicked on a colour. If greater, it had to be a size (or beyond the end).

Selected colours and selected sizes were stored in two variables called currentColour and currentSize respectively and used within the draw() function when creating our circles.

Featured Artwork

Mark suggested that people draw a portrait of me to test our new program and there were some brilliant renderedings. Three people were kind enough to share theirs with me so that I could put them here. I think they’re great!


The files for this week can be found on our GitHub repository.

Creators: Robot Arm


This week we looked at a representation of a robot arm. The body of our robot is allowed to slide horizontally and the arm can pivot at the shoulder (where the upper arm attaches to the body) and at the elbow (where the lower arm attaches to the upper arm).


An important point about this project was to show how transformations add up together. Transformations include translations (moving in straight line), rotations (turning about a pivot point) and scaling (changing size). We’ve used translations and rotations for our robot.

In P5, the origin, or place where the x and y coordinates are both zero is at the upper left-hand corner of the screen. The x coordinate gets bigger as we move right and the y coordinate gets bigger as we move down.

When we translate, we move the origin to somewhere else. This is handy for a few reasons but if we are performing rotations. All rotations happen around the origin, wherever that happens to be at the time.

This diagram shows all the transformations we use for our robot:

Robot DOFs (1)

  1. Translate to move the origin to the centre of the robot body
  2. Translate to move the origin to the shoulder
  3. Upper arm rotation at the shoulder
  4. Translate to move the origin to the elbow
  5. Lower arm rotation at the elbow

Because these transformations stack up on top of each other, this is what each part experiences:

  1. Body – Transformations: 1
  2. Upper Arm – Transformations: 1, 2, 3
  3. Lower Arm – Transformations: 1, 2, 3, 4, 5

The body is only affected by one, but the lower arm is affected by all five.


To move the robot, we set up three variables:

  1. bodyPos to store the body position (our first transformation)
  2. upperArmAngle to store the rotation at the shoulder (our third transformation)
  3. lowerArmAngle to store the rotation at the elbow (our fifth transformation)

We created a function called handleInput() called from the draw() function (which is called every frame). In that we used the keyIsDown() function from P5 to check for keys being held down. We made the left/right arrow keys move the body horizontally, the up/down arrow keys rotate at the shoulder and the Z/X keys to rotate at the elbow.

Source Code

As always, the code can be downloaded from our GitHub repository.

Creators: Snake

This week we looked at creating a user-steerable snake in the style of the classic phone game.


Image from James Hamilton-Martin, Flickr

Things we need

The snakes head moves and the rest of the snake’s body is made up of places the head’s already been, up to a certain point. For this we use a JavaScript array (we’ve also called it a list at times).

We don’t want the snake’s length to grow indefinitely, so we have a maximum length. Once the list of stored locations gets larger than this, we use the JavaScript splice() command to remove the first (oldest) element from the list.

Direction and turning

Screen Shot 2018-02-06 at 22.59.28

We assign numbers to represent directions on the screen. Zero is right, one is up, two is left and three is down. Note then that if the snake is heading right (in the screen sense) and turns left it goes to up (in the screen sense); direction goes from zero to one. Similarly, if going up (in the screen sense) and it turns left then it goes to left (in the screen sense).

Generally then we note that turning to the left makes the direction number get bigger while turning to the right makes it get smaller. This rule hold until we get to a number bigger than three or smaller than zero; these make no sense. If direction is at zero and the snake goes right, we set direction to three. Similarly, if direction is at three and we turn left, we set direction to zero.

Getting this week’s code

As always, all the code from our Creator group can be found on our GitHub repository.

Creators: Spirograph

This week in the Creators group we looked at emulating the classic toy, the Spirograph.


The Spirograph consists of geared plastic discs. One disc is fixed in place over a sheet of paper and the other, with a pencil tracing the path, is allowed to spin around it. The result is a complex and beautiful design on the paper.

Screen Shot 2018-01-30 at 17.04.14

This diagram should help explain in conjunction with the photo. The centre of the black disc spins around the centre of the red disc, which itself doesn’t move. So the centre of the black disc rotates around in a circle. Pretty simple?

Now, the pencil itself rotates around the centre of the black disc. Shouldn’t that make a circle too? Well it would if the black disc wasn’t moving. Thankfully though, it is and that’s what makes this interesting.

Finding the Location of the “Pencil”

So how do we find the location of the pencil? Let’s look at our diagram again, but with things re-labeled a bit:

Screen Shot 2018-01-30 at 17.33.58

  • Centre: Formerly “centre of red disc”. It’s the fixed centre of our spirograph
  • Centre2: Formerly “centre of black disk”
  • Point: The point on our curve. This is where the pencil would be in a physical spirograph.
  • Radius0: Distance from Centre to Centre2
  • Radius1:Distance from Centre2 to Point
  • Angle0: The current angle of the line between Centre and Centre2
  • Speed0: The amount that angle0 increases every time we draw
  • Angle1: The current angle of the line between Centre2 and Point
  • Speed1: The amount that angle1 increases each time we draw

So at any time the location of our point is:

Point = Centre + [Centre2 relative to Centre] + [Point relative to Centre2]

So know where Centre is and if we can calculate where Centre2 is relative to Centre and similarly where Point is relative to Centre2, we can just add them all together!

Given an angle and a distance, can we get a location?

The answer to this is a resounding “yes”! Look at the diagram:

Screen Shot 2018-01-30 at 17.56.34

given an angle and a radius, we can calculate the X and Y position of any point around a circle. The magic is the COS and SIN (pronounced “kos” and “sign”) functions. These functions exist in almost all programming languages and JavaScript’s no exception.

Using p5.Vector

The last big concept we tackled thus week was using P5js’s built-in vector class to store (x, y) points and make our code tidier. To make a vector we just use createVector(x, y). We can then use functions to add them together, etc. We would get the same result working with the X and Y values separately but the code is a lot neater and shorter.

And in conclusion

This looks pretty cool:


Getting this week’s code

As aways, all the code from our Creator group can be found on our GitHub repository.


Creators – Being Random

Screen Shot 2017-10-17 at 00.56.49

This week we mainly looked at three things:

  • How data is organised on your computer
  • Creating functions
  • Using randomness to make things interesting

Data Organisation

Most of us had heard of a hard-disk before. This is a stack of metal disks inside your computer. Each metal disk has a special coating made of millions of tiny magnets (like you might find stuck to the fridge) that can be turned on and off.11644419853_9499fa0faa_b

We saw that able to turn something on and off, like a switch, was enough to count from zero to one, but the more switches we added, the higher we could count. Two switches can count from zero to three:

Switch 1          | Switch 2          | Total (Add)
[Off = 0, On = 1] | [Off = 0, On = 2] |
Off = 0           | Off = 0           | 0
On  = 1           | Off = 0           | 1
Off = 0           | On  = 2           | 2
On  = 1           | On  = 2           | 3

With enough of these tiny switches, we can store anything we need. Each of these tiny switches is also known as a ‘bit’ and a 1 terabyte hard disk has a billion of them!

We also saw that the files on your disk are arranged with folders (also known as directories). Folders can contain both files and more folders. This allow us to keep our hard disk organised; without them all our files would be in the same place which would be difficult once we had more than a few. The location of a file is called its “path”. Looking at the highlighted file on the desktop of my Mac we can see the full path would be:

Screen Shot 2017-10-16 at 22.19.59

/Users/kierancoughlan/Desktop/Ball and Bat Sounds.m4a


This means that, reading backwards, the file called ‘Bat and Ball Sounds.m4a’ is in a folder called ‘Desktop’ which is itself inside a folder called ‘kierancoughlan’ which is, at the highest level, inside a folder called ‘Users’.


A function is a collection of commands that do a job together. We’ve already encountered them, even if you hadn’t especially noticed:

  • Our P5 template already contains two functions called start() and draw()
  • All of the P5 commands we have used, such as createCanvas() and rect() are functions themselves

We could add all our code to start() and draw(), in fact, that’s what we’ve done before this week. That’s fine starting out, but it does mean, once there are a lot of commands in those functions, that our code is gets harder to read and understand. Breaking out a few commands into a new function and giving it a name that describes what it is doing, really helps.

Once we’ve written a function, it can be called as many times, and from as many places, we as need.

Functions can do one other thing too: they can give back a value to the place where they were called from. For this we use the special word return. For example, let’s see what a function to pick the largest of two numbers, we’ll call it Max(), might look like:

function start(){
    let a = 4;
    let b = 10;
    let c = Max(a, b);

function Max(n1, n2){
    if (n1 > n2)
        return n1;
        return n2;

We give Max() the two numbers we are comparing. If the first one is bigger than the second, it gives back the first. Otherwise, if gives back the second. Note too that the names of the variables in Max() are different to those in start(), and that’s not a problem.


Finally, we looked at the P5 function random(). We used it two different ways:

random(); // gives a number between 0...1
random(n); // gives a number between 0...n (where n is a number!)

In the first form, we used it to pick a random colour. In the second, we used it to pick a random position for our squares.


As usual, all the code is on the creators github repository. Head there and download it!! The files for this week contain both the script we wrote (sketch.js) and a longer version that I wrote (sketch2.js). Feel free to take a look at both!