Creators: General Zod 3D!

This week in Creators we explored 3D and build an animation or two using it.  The final one was a “General Zod” simulation where we recreated a scene from a classic movie

Check it out here!

general-zod

This scene used the following elements:

  1. 3D Canvas! Our canvas was set up to use WEBGL – enabling this means you can use the 3D capabilities and shapes of p5
  2. Shapes – just the two shapes here:
    1. a “Box” which is your floating “prison”
    2. an “ellipsoid” which represents Krypton
  3. Lights!
    1. We looked at the different types of lights in WebGL (ambientLights, pointLights and directionLights) and for this scene I went with a few directionLights to light things from various directions
  4. Action!
    1. Positioning and moving the shapes is performed by transforms.  We moved the rather large planet to the bottom with translate and made the prison rotate and vanish off into space with a few rotate statements.
    2. Note that with 3D stuff, we have the use of a rotateX, rotateY, rotateZ since we can rotate in lots of ways!  I also added a rotation to Krypton above to make it more realistic.
  5. Texture!
    1. Krypton: We looked at adding textures which is an image that you paste onto the object.  The sphere above is textures with an image of Mars I found – not sure what Krypton is like I but I picture it as kind of orang-ish.
    2. Prison: For texturing the prison we did the same thing, but with a difference!  It still is using an image as the texture but it’s using the p5.dom library to control the web camera and take pictures from that every frame.  This allowed us to place ourselves “live” in the scene.

It is pretty amazing the animations and effects you can create with very little code using the p5 webGL library.  Happy coding!

Creators: Drumtown!

Today in Creators we played a bit more with sound and built a type of musical instrument using Javascript.  The project was called “Drum Town” because it was based on the idea of a music mad building and when you wake up one of the resident’s by clicking their window, they would play a particular sound every time some traffic cruised past.  Each floor consists of people with the same instrument.  What else would they do?

Play the finished Project by clicking here! – Make sure to TURN UP THE SOUND!!

drumtown

How did we build it?

The awesome thing at this stage is that the group has become so competent at javascript that as soon as we had the idea, some people put their heads down and started building without a whole lot of direction!!  I won’t go into the ins and outs here, but the code is up on our repository and you can go through it!

Interesting bits!

Some of the interesting bits of the project are:

  1. Classes:
    As usual we needed a few classes – this time we used classes for the Car and the Window.  The basic idea was to have a car moving at a constant speed left to right and to have windows that play a sound whenever the car goes past.
  2. Unicode Sprite Characters!
    We learned that now text is getting more and more graphical – we can see it on our phones with emoticons.  There are a large amount of emoticons in standard fonts and if you enable the windows keyboard (right-click taskbar and choose “Show Keyboard” you get on onscreen keyboard that can type all sorts of characters – we used these for our cars:  and could write crazy looking code like:  this.carList= [🚗, 🚚, 🚛, 🚕, 🚜]; .  This will make it REALLY easy for us to write games with nice looking costumes without messing with images.
  3. Sounds:
    I handed out some sounds for us but you can put whatever sounds you like in your own version.  I got my sounds from this website here which has TONS of free instrument sounds!  We named the sounds 0-6.wav to make it easier to use loops to reference them.

That’s it!  Take a read through the code, I finished it off a little before pushing (mainly added a title).  It would be great to make your own version with a different them and a different set of sounds perhaps.  Also – maybe this can give you ideas for other types of musical instrument that you can create, perhaps with a completely different model. Have fun with the emoticons too 📯🎷🎺🎸🎻!

Creators: Autonomous Agents!

This week in Creators we did a very fun project – we learned how to simulate creatures with a kind of basic artificial intelligence and their own hopes, dreams and aspirations!  We made an app where a bunch of creatures desired to spell the word “Creators” and were also scared of the mouse.

Click on the image below to play with our completed animation.

creature-steering

All the code is on the creators github as usual! Pretty cool eh?  How did we get it working?

The evolution of Consciousness
At the start we chatted about an interesting channel on youtube called Kurzgesagt which contains short videos on all sorts of interesting topics.  A recent video I watched discussed the notion of consciousness and how it might have evolved and it inspired the project.  Though a lot is speculation about this topic, the video made a reasonable argument that consciousness evolved as a survival tool to allow simple creatures to seek energy (food) and flee from creatures that wanted to eat them.  Watch the video, it’s very good!

Though we aren’t quite at the stage where we are ready to code up conscious beings – it was interesting to think about how we might add needs and desires to a character, so that’s what we looked at!

Reynold’s Steering Behaviours for Autonomous Characters
Having decided that we wanted some creatures that moved to the beat of their own drum, we next needed to figure out how to implement it.  There are LOTS of pretty complicated strategies for simulating intelligence, but we looked at a brilliant research paper published in 1999 by a playstation programmer called Craig Reynolds called Steering Behaviours for Autonomous characters – read the full paper here.  In this paper, Reynolds describes a simple but fantastic way to model “autonomous” characters using forces.

steering2

An “Autonomous” character is one that controls or powers itself – i.e. there is no remote control here! There is a lot in Reynolds paper but the basic idea is to think of some “behaviours” that a creature might exhibit – these could be:

  • Flee: perhaps the creature might want to escape from someone?
  • Seek: perhaps the creature might want to get somewhere really quickly?
  • Arrive: perhaps a creature might want to get somewhere and stay there (i.e. slow down to “arrive” there.
  • Be close to other creatures: perhaps a creature might want to be close to creatures like them
  • etc – basically anything you can think of nearly!

In Reynold’s paper, creatures generally have a limited vision, and can have more than one behaviour happening at once – i.e. I really want to get food, but want to avoid the predator in the way.

The simple but powerful that Reynolds came up with is the idea of using forces to describe these behaviours and letting newton sort it out.  To model a Reynolds behaviour, you:

  1. Determine your DESIRED velocity for this behaviour – this is a force describing how badly you want to escape the predator, or pursue the target, or avoid the obstacle, etc
  2. You STEERING force vector is worked out as:

steering = desired – velocity

With this simple looking formula, and behaviour rules you combine, you can create some great behaviours that can seem to have realistic looking intelligence behind them.

The Code
Because Reynolds uses force, we had an object which could be a good starting point developed way back in Week 8 – our fun with forces model was a perfect starting point since we already had a “Mover” object that had an applyForce function to allow you to add a force to it.

seek-fleeOur movers “seek” home and “flee” the mouse

All we needed to do was to add some “personality” to our Mover so that it decided itself where it wanted to move to.  These are called “behaviours” in Reynolds brilliant paper.  We decided that our first Mover would have a “timid, homebird” personality and it would have two desires: to get home (some location that is dear to it!), and to stay away from the mouse.  We decided that when it is “afraid” of the mouse we should add something visual to let us know it was afraid – we coloured it red.

The first and easiest code to add was the code to make the Mover want to go home:

 goHome(){
    // i want to go home
    let desired = p5.Vector.sub(this.home, this.position);
    desired = desired.limit(this.maxSpeed);
    let steering = p5.Vector.sub(desired, this.velocity);
    this.applyForce(steering);
}
This is a good example of the process – first we create a Vector that describes where we want to go (home – location), next we limit it to the maximum speed of the Mover.  Next we use the magic formula of Steering = Desired – Velocity to find what the steering force should be.  (This looked okay for us, but in Reynold’s paper he recommended a maximum steering force so it doesn’t steer too quickly – good idea but we didn’t bother with it!).  We called this “goHome” but Reynolds calls this the “Seek” behaviour.
 flee(){
     // i am scared of the mouse
     let mousePosition = createVector(mouseX, mouseY);
     let desired = p5.Vector.sub(this.position, mousePosition);
     let dist = desired.mag();
     if(dist < 100){
         desired = desired.limit(this.maxSpeed);
         let steering = p5.Vector.sub(desired, this.velocity);
         this.applyForce(steering.mult(10));
         this.isAfraid=true;
     } else {
         this.isAfraid = false;
     }
}
The next steering behaviour was fear of the mouse.  We added this as per the above “flee” method.  We imagined that our little creatures can see the mouse when it’s 100 pixels away, and if it is, then it’s afraid and a very strong “flee” force is present.  In the show method we decided to show the fear by turning it red (we should have drawn e.g. a scared face or something).
Finally, we add a function which calls the behaviours in turn:
applyBehaviours(){
    this.flee();
    this.goHome();
}
In each draw loop instance, we call the applyBehaviours, just like we call the “move” method and the “show” one.
That’s it!  That’s all it took to give our creatures the desired behaviours!
Drawing a message:
The code to draw a message came from a hidden feature of the font class in p5 – the ability to get points from text with textToPoints.  This allowed us to get a bunch of points to set as home which spelled a message.   Depending on your computer, it could run a little slow so you might want to just add every 2nd points (takes a while to paint on my phone, but looks quite good on my laptop!).
function preload(){
    font = loadFont("fonts/AvenirNextLTW01-Medium.ttf");
}

function setup() {
    createCanvas(innerWidth, innerHeight);
    textFont(font);
    points = font.textToPoints("Creators", 100, height/2, 300);
    
    for(let i=0; i< points.length; i++){
        let startPosition=createVector(points[i].x, points[i].y);
        movers.push(new Mover(random(10,30), startPosition));
    }
}

Creators: Shootah Part 2 – Sound and Bullets

This week we carried on our “Shootah” space shooting game  by adding some bullets with an appropriate sound effect.  This brings the game to the stage shown below:

Not very snazzy but it’s starting to show some promise!

As with last week, this will only run if served up from a web server, we had a few ninjas in that missed last week and had to install node.js and local-web-server application.

Bullets!

Our Bullets were a pretty simple object that just moves up constantly – this has the following code:

class Bullet {
    constructor(x, y){
        this.x = x;
        this.y = y;        
        this.speed = 10;
    }

    move(){
        this.y = this.y - this.speed;
    }

    show(){
        push();
        fill("yellow");
        ellipse(this.x, this.y, 10, 10);
        pop();
    }
}

We created an array of bullets and added a new one to the array each time the up arrow is pressed.  In addition, we played a “firing” sound which really adds to the feeling:

function preload(){
   playerImage = loadImage("images/spaceship.png");
   bulletSound = loadSound("sound/laser.mp3");
}

function draw() {
  // .... skipping a few lines
  for(let i=0; i< bullets.length; i++){
     bullets[i].move();
     bullets[i].show();
  }
  // .... skipping a few lines
}

function keyPressed(){
   if(keyCode==UP_ARROW){
   bullets.push(new Bullet(player.x, player.y));
   bulletSound.play();
 }
}

 

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!
  • We need to keep and display a score
  • We need a way to die.. perhaps the enemies can drop bombs?
  • Other ideas:
    • Maybe a background tune in a loop?
    • Maybe a scrolling starfield in the background?
    • Maybe multiple levels?
    • Maybe different types of enemies?
    • Maybe a shield?
    • Perhaps some different weapons or weapons you can pick up?

We have gotten this far so we might as well push forward and make this a fully working game so we’ll get some of the above sorted next week!  The code is as usual up on our github.  https://github.com/coderdojoathenry/creators2018

 

 

 

Creators: Images and Web Servers

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:

file:///C:/Users/markdav/code/dojo/creators2018/Week11-shootah/index.html

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

nodejslogo

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.

We installed node.js from the node website here.

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”

markdav@markdav2017 MINGW64 ~/code/dojo/creators2018/Week11-shootah (master)
$ ws
Serving at http://markdav2017:8000, http://192.168.71.1:8000, http://192.168.48.1:8000, http://192.168.1.20:8000, http://127.0.0.1:8000

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):

big-spaceship

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:

let playerImage;

function preload(){

      playerImage = loadImage("images/big-spaceship.png");

}

Once we had the image loaded, we could draw it using the “image” function.   The show function on our player used this to paint the image:

show(){
    imageMode(CENTER);
    image(this.img, this.x, height-100, 100, 100);
}

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!

shooter-1

 

Creators: Introducing Force

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

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!

Continue reading

Creators: Objects and Vectors!

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”.

vector-add3

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!

This web page has some nice details on the maths behind vectors.

 

Position, Velocity and Acceleration

We saw that position, velocity and acceleration are really common uses of vectors.

Continue reading

Bouncing around in Javascript

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!

 

Creators: Creative Coding with p5.js

What is P5?

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:

Continue reading

Creators Quiz Time

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.