The sound was done very similarly to the image – we created a folder (sound) and added a sound file we found on the internet to the folder. In the preload function we loaded the sound from the file into a variable (“bulletSound”). In the keyPressed function, we check if the pressed key is UP ARROW and if so, we play the sound and add a new bullet to the list.. voila!

Problems to work on!

A great start but a lot left to be sorted with this game! Here are some of the items:

The bullets array grows forever – this really starts to slow down the game as we keep playing it. We need to add some code to remove a bullet from the array when it is gone off the screen.

The player has no edge detection – we need some way to keep it onscreen.

We need some enemies!!

We need to get the bullets to check when they are hitting the enemies!

Up to this point in Creators we have been building all of our apps as sketches ourselves using the drawing functions in p5/javascript – ellipse, rect, etc. This is great but a question we get all the time is “how can I load IMAGES and Sound into my games?”. This week we got stuck into this, using a project of a very basic shooting game as an example.

However, before we got stuck into writing our game, we needed to install something on our computers called a web server.

What is a web server and why do we need it?

A web server is a program that makes files available on the internet. Mostly, the files are made available to programs that can understand the Hyper Text Transfer Protocol – or http for short. “http” probably sounds familiar – this is because you are used to seeing it on your browser before internet links.

Up until this point, we simply opened files on our computer with explorer and if you looked at the browser link you would see something like this:

The “file” at the start means the browser is opening a file on the local computer. This works great for a lot of things, however if you write a program in javascript which runs on the computer, javascript is not allowed to open files on the local computer. Why? Because if javascript could open files on the computer of the person opening a website, it would be easy to write a webpage that steals information from people looking at it, without them knowing it. This would be a BIG security problem!!

Javascript can only open files which are served out by a web server – so in order to load images or sound into a javascript program, we need to make sure that they are served out by a web server.

Installing our Web Server – Node.js

There are lots and lots of web server programs out there but we decided to install one which is written in javascript – we are javascript nuts after all! Node.js isn’t actually a web server, but is a set of programs kind of like p5 that make it easy to write or install programs in javascript for your computer – and especially ones like web servers. Later in the year we will play some more with node.js and write our own programs in it to do some cool stuff.

Once we installed node.js, we then installed a web server which is written in node.js – we installed one called “local web server”. To install local web server – we opened a command terminal in the computer and typed the following:

npm install -g local-web-server

npm stands for “Node Package Manager” and it’s a program that makes it easy to install programs written in node on your computer. Once this was done, we have a new command in our computer – the command is “ws” and what it does is to start a web server that puts the files from the current folder on the internet!

To try it out, we started a new p5 project called “shootah” and right clicked on the folder and selected “open in terminal”. The command prompt appears directly in Visual Studio Code, which is handy. We then typed “ws”

This started a web server in the folder which serves out the files – to open we used either one of the links given, or actually we kind of preferred to type “http://localhost:8000&#8221; which was another way of putting it. When we did this, the files just showed in the browser!

Developing Shootah

All this installing took us some time, but we were ready to get stuck into developing our space shooting game. We go to the stage of getting a Spaceship which we could move left and right – but no bullets, sound or enemies, yet.

First we needed a spaceship picture, and we had a bit of fun rooting around on the internet for one. Some people created their own images. I ended up picking this picture (you can right-click this picture and save it if you like it too):

When we had the spaceship picture, we created a folder to store our pictures. I created a folder called “images” and put the picture in there and called it big-spaceship.png. Some others called their folder “assets” which is a term you often see used. To be honest my picture was a bit big – you are better off making the images just the right size, as it saves a little bit on memory for the computer when showing them.

We learned that there is another special function in p5 which is best to use when we are loading files like sounds and images into variables – it’s called “preload” and we wrote the code to load our images in there:

Aside from that, the code was pretty similar to other sketches we have done. We put some basic code in to allow the player to be moved left and right. This is as far as we’ve gotten – next week we’ll work on it some more and see if we can get some enemies, bullets, sounds, maybe stars, scores, better movement, etc. Code is on github as usual!

Last week in Creators, we looked at Vectors and how they can be used to specify things like position, velocity and acceleration. This week, we looked at what can actually cause something to accelerate – FORCE! First we talked and played a bit with force and then we created a simulation of something that we could apply different forces to. We wanted to think about a scene where we had lots of objects and different forces acting like wind, gravity, friction, etc.

What the heck IS force?

We started off by looking at the laws of motion from Sir Isaac Newton, who was the first guy to think hard about this (or at least to come up with good theories). Everyone knew about the apple but not many about what it made him think of. We googled his laws of motion and arrived at a NASA web Page that had a nice short explanation:

Newton’s laws of Motion (NASA)

Like all great ideas, these look obvious when you know the answer, but were huge ideas at the time! I’ll butcher the above laws by trying to re-word them to capture the interesting thing about them from our point of view!

This week in Creators we covered a few very important concepts which we will likely need to run over a few times until we get them solid!

What are Vectors?

First we looked into a concept called Vectors, in particular 2D Vectors. We saw that at the most basic, a Vector is a simple way of holding an x and a y in one variable. This is useful for keeping track of the position of an object as you only need to keep one variable e.g. “rocketPosition” rather than two “rocket_x, rocket_y”.

The other thing we talked about is how this X and Y can represent a change in a given direction – i.e. a vector with x=10 and y=5 can mean “change X by 10 and y by 5”. This way it’s useful for ANYTHING that might be in a given direction – things like velocity and acceleration for example!

The other thing cool about the vector object in p5 is that it has a bunch of functions that allow you to add, subtract, etc them. This would allow you to e.g. add a velocity vector to a position vector to come up with a new position vector!

Position, Velocity and Acceleration

This week we looked at animations, and how to make objects move in p5.js.

We covered:

How to animate things in p5

Some mouse interaction

Animation in javascript (or all programming really!) is basically changing some variables in the draw function before we actually draw the object. If we change each variable by a little bit, it looks like smooth movements, just like a cartoon!

To save some typing, there is a video below with a quick overview of what we did:

Okay, it’s pretty simple stuff and not exactly the most exciting animation in the world, but you guys did some playing around and came up with several interesting variations and now we know how to do it, the sky is the absolute limit on what we can build 🙂 !

As usual, the code is up on the github to be pulled down and played with or changed to your heart’s content!

This week we looked at p5.js – a library to make creative coding in javascript MUCH easier! We first downloaded and copied p5.js onto our computers, and copied it into a new project folder. We included p5.js in a html file, just like we included our own javascript file last week.

In fact, we looked at the file and realised that p5 is just another javascript file, just like the one we wrote – the code is long and looked a bit complicated, but it was basically the same kind of thing.

But really, what is P5?

p5 is a set of functions that make it easy to write programs for the most interesting parts of javascript! Mainly, for drawing and animating things on a webpage, but also for sound, and other stuff. If has lots of functions for:

This week at Creators we took some time out to play some games and do some quizzes – well done to everyone that took part! We used the fantastic website “Kahoot!” to drive the quizzes. Some of you had used this site before in school. We had a little trouble getting it going due to network trouble, etc but got it sorted and interestingly saw how we could debug the issues in the kahoot javascript using the console to see that it was the network causing the problems, just like we did with our own code.

Anyhow the results of the quiz are below – everyone did brilliantly as expected but LORD PJO showed her quickfire dominance by amazingly winning two of the three games:

We then did a rapid-fire challenge to do a circle that changes color when the mouse is over it. This is one of those ones that is easy in scratch (“touching mouse”) but we hadn’t covered collision detection really in javascript so you had to figure it out. Most all of you got it, some with really clever solutions! My pretty simplistic solution is checked up to github as usual.

Next week we have a break and then we plan to spend a week working on our own ideas – anything you like – either bring in a project that you are working on and Kieran and I will try to give advice or just start a new one in the class and we’ll try to get you off on a good footing.

This week we looked at WebGL and how it can be used in Javascript to easily create 3D animations and games. After looking at different shapes for a while, someone suggested building a solar system so that’s what we did! This project just did the first sample planet.

What is WebGL?

WebGL is a javascript API that allows your programs to use the graphic cards on your computer. Graphics cards are built for really fast graphics and have specially encoded hardware to quickly do the calculations needed for common graphics. With 2D, you can often get away without graphics cards, but they really make things a lot faster in 3D!

There are several javascript libraries that let you use webGL – the most famous and probably the best of them is one called three.js, which lets you do really advanced 3d – however our trusty p5.js also has a pretty decent set of functions and for us is much easier to use.

Initializing the p5 canvas for 3D

The great thing we found about p5.js 3d is that is is REALLY similar to the 2D shape functions, so much so that we all intuitively were able to get going with little need to look at documentation.

Sadly, it’s not easy to mix 2D and 3D code in P5 as the “canvas” is created differently.

To get it started, we had to add one word to the createCanvas function call – “WEBGL” – so to create a canvas we use the function:

setup() {
createCanvas(800, 600, WEBGL);
}

P5 3D primitives

There are many better reference guides online so I won’t go int great detail here but the main built-in shapes that you can use to create things with are:

Box for all manners of cuboids

Plane for a flat plane (a “rect” also works actually!)

Sphere for a (duh!) sphere

Ellipsoid for a rugby ball shaped thing

Cone for a cone-shape

Torus for a donut shape

Cylinder for a cylinder

Using these basic building blocks, it’s possible to create all manner of shapes.

There is also a “loadModel” function that allows you to read in a model from a 3D package like “Blender”. These can be models of spaceships, bad-guys, houses, ponies, whatever you like! Maybe at some stage in the future we’ll try to learn a bit about blender. One of the ninjas already had played with blended and managed to load in a model of a meteorite he’d been working on!

Positioning shapes

The models and shapes don’t have any coordinates on them – it’s all stuff like size and grid size.

Our first program involved creating a box and moving it around.

To position the shapes you use the “translate” function, just like you can in 2d. With this we moved the shape around

The box appeared in the center of the screen – i.e. 0,0 is the middle of the screen (like scratch) rather than the top left. (Box 1 below)

Making X bigger moved it to the right (Box 2)

That making Y bigger still moved it “down” unlike scratch! (Box 3)

That making Z bigger moved it towards the viewer (Box 4)

That there is perspective automatically built in

To Rotate shapes, there are three functions that are handy: rotateX, rotateY, rotateZ – these can rotate around the axes. Just like in 2D the ddefault unit is radians so you need to set angleMode(DEGREES) if you want degrees. For example – rotating the box by 45 degrees is per below:

angleMode(DEGREES);
rotateX(45);
box(50, 50, 50);

Push() and pop() can be used to stack the transformations on top of each other – just like in the 2d sketches!

Lights!

We learnt that there are three types of light:

AmbientLight is light which comes from everywhere – it casts no shadow. We just give it a color ambientLight(255) is a white ambient light for example

pointLight is a light which is centered on a point. It just has a color and a position – e.g. pointLight(r, g, b, x, y, z). Pointlights are pretty dim, but you can stack lots of them on the same location to make them brighter – this is what we did for our sun!

directionalLight is a light which has a color and a direction – this is very similar to the pointLight except that the light just shines in one direction and can be used for e.g. spotlights.

Material!

Depending on the material, the light reflects different ways – the main material types we tried were:

ambientMaterial: This is normal “Matte” material

specularMaterial: this is reflective material – it shines back like glass or water

normalMaterial: This is the default material type – this is kind of weird looking to me and I’d usually use ambient…

For each of these types, you simply set the material before drawing the shape – kind of like the fill function.

Explaining the Solar System Code

Our “Solar System” code was very basic – what we have here was one planet orbiting around a Sun in a spherical orbit, with a moon orbiting around that planet. We didn’t have any physics in there – just spheres orbiting each other.

Challenge!!

We did one planet and moon in the class because a lot of the time was spent playing with our own projects. How about you take our solar system and change it so that all the planets have accurate relative rotation speeds? i.e.

This week in Creators we looked at a brand new concept – functions that actually call themselves – also known as recursion.

Though this seems at first glance like a really silly thing to do, we were quickly able to use it to generate some pretty effects.

The main things to remember about the recursion are:

1. Make sure to give it something that will let it exit – a function calling itself forever will not work and the browser will crash or throw an error. For us, we passed a value as a parameter and made it smaller each time, exiting when it fell below a certain value.

2. Do the math! Recursion leads to big numbers of operations very quickly and can slow down or crash a browser easily. Make sure to save often and think about the amount of times your function will run.

Recursion is really handy for cases where there are lots of operations that are similar.

Circle Pattern Project

In this project, we wrote a function which draws a shape (we picked a circle) before calling itself three times to draw the shape to the left, right and below. The code is below:

Notice the If statement? This means that it will not bother drawing circles smaller than 5 pixels in diameter – this allows the code to work.

This simple code generated the following pretty fractal:

Fractal Tree

For the next project, we used very similar code to create a beautiful fractal tree. In this case we wrote a “drawBranch” function which can draw a branch at a given angle and length.

We added a little code to allow us to change the angle that the branches fan at – the fanangle – dynamically. Depending on the variables, we could slow down our computer quite easily – the trick is to think about how many lines your computer will need to draw.

Each function called itself to draw a pair of smaller branches off of it. The tree is shown below – just before I checked the code in, I added a little if statement to color the branched brown if the length is > 50. The result is below:

This looks quite pretty and is fun to play with if you have a pretty fast computer – play with it here:

This week in advancers, we simulated a true story! Once Mark was driving past Athlone and encountered a car driving the wrong way down the motorway. In this case it was a poor old gentleman who had somehow ended up turning down the sliproad, but we wrote a game which simulated the incident from a crazier drivers point of view!

The idea of the game was to drive as far as possible the wrong way down a 4-lane motorway before you crash.

Step 1: Draw the car

Out first step was to draw a car – we did this by switching to “Vector” mode and dragging a few boxes together – this is mark’s car below:

Step 2: Draw the road

The next step was to draw the road – the road was drawn the same way, using vectors. One key point here was to space out the lanes more or less evenly, and to use the “Shift” button to ensure that the lines on the road were at 90 degree angles. We drew the gaps in the white line using grey lines the same colour as the road. A few bushes and buildings completed the scene!

Step 2: Make the road scroll!

In this game, we wanted the road to scroll from top to bottom. This meant that the ySpeed of the road was negative. We also wanted the road to move back to the top whenever it got to the bottom. We had done side-scrolling with multiple sprites year ago in Explorers, and this was the same idea – however we managed to do it with just one sprite by using clones in the code below:

Step 4: Make the Car Move!

In this step we started off with basic movement – we were going to get to more realistic physics, but ran out of time! I’ll see if I can show the code for this at the bottom and you can add it in yourself!

To make it move, we just checked for left and right arrows and added speed accordingly:

Step 5: Enemies!

The game was already starting to feel fun, but it’s a lot better with some unsuspecting traffic on the road! We cloned the “player” sprite, and created a bunch of costumes to represent different styles of vehicle:

Next we wrote some code VERY similar to the scrolling background code for the enemy – this also reappears at the top when it reaches the edge – the difference being that it appears in a random lane and with a new costume. This turned out great!

Final Step: Game Over

The final step was a “Game Over” text sprite – this shows whenever the player crashes!

This was a really fun game – I enjoyed making it a lot!

Exercise: Realistic Turning Physics

I said I’d have a go at realistic turning physics for the car – this code works and looks great – try adding it to your game to see what you think – basically it turns the front of the car realistically and the back skids around like a real front-wheel-drive car. It was a bit tricky so I’m glad I didn’t push it as people would have gotten really tired as I tried and failed a few times! Just pop this code into your “player” script anywhere near the end!