Intro to p5js

Welcome! This is an introduction to programming in p5js.

p5js is a a programming language and environment sort of halfway between processing.org and JavaScript. The advantage is you can just write it in your browser and see the result instantly.

Other links you may need:

Evaluation afterwards | Fablab Facebook - follow for announcements of open courses | Instagram @fablabruc | Humtek Facebook Page | Humtek Facebook group | [Version of this guide for Processing on your computer] (https://fablab.ruc.dk/introduction-to-processing/)

The goal is to have a simple interaction up and running in a 45 min lecture. An instructor will help you through the different exercises and explain the different parts of the code. You should follow the instructor, but if something doesn't work as it should or you have questions just ask for help.

If you missed the code the instructor has written, you can always see all the code on the bottom of this page.

Introduction to p5js

#1

You are going to program a Flappy Unicorn game.

Like Flappy Birds, you may end up a millionaire.

#1 Setup

a) Save these two images to your computer:

right-click on the image and choose "save image as". You probably want to save it in your "downloads" folder.

b) Visit https://editor.p5js.org

c) Click on "sign up", top right hand corner

Create an account.

d) Rename the project to a suitable name, plus a version number. For example flappy01

e) Click on file -> save

f) Click on this arrow to unfold the files column

g) Click on the small down arrow and choose "Upload file"

h) Upload the unicorn.png file

i) Do it again and upload the background.jpg file

You are now ready to copy-paste your first program into the p5js editor window:

(Note: remember you need to start with a blank sketch)

let backgroundImage;

function preload() {  
  backgroundImage = loadImage("background.jpg");
}

function setup() {  
  createCanvas(600, 350);
}

function draw() {  
  // Top-left corner of the img is at (0, 0)
  // Width and height of the canvas
  image(backgroundImage, 0, 0, width, height);
}

Now press the play button in p5js.

Your browser window should now look like this:

Yeah! You've got a background for you game!

This is the basic structure of a p5js sketch.

  • Some variables
  • The function preload() gets some things ready
  • The function setup() runs once when the program starts
  • The function draw() is run about 60 times a second. So this is a good place to put things that move, need updating etc.

#2

Now load the unicorn image into your program. Notice the code you have copied for the background image. The approach for a new image is the same:

· Make a variable with the variable type let at the top of your program:

let unicornImage;

· Load the image in preload() : unicornImage = loadImage("unicorn.png");

· Finally draw your image with given coordinates and size. Use: image(unicornImage, x position, y position, width, height);

#3

Make the Flappy Unicorn fly and fall

Have in mind that the 0,0 point in p5js is on the upper left corner of the window.

Make a variable of type let that can be used to define the unicorns Y position.

Make this variable decrease its value every time the draw method runs (this makes the unicorn 'fall') and increase the variable's value if a key is pressed by using keyPressed (this makes the unicorn ascend).

Note that you have to click in the preview window for the program to register the keypress.

Code tip:

let yUnicorn = 200; //make a variable and give it a value

function keyPressed() {  
  yUnicorn = yUnicorn - 10; // yUnicorn decreases by 10.
}

function draw(){

yUnicorn = yUnicorn + 1 ; // yUnicorn increases by 1.  
image(unicornImage,100,yUnicorn, 50,50); //draws unicorn  
}

// remember you already had a line that draws the unicorn - either delete that line or modify it to be like this line.

Notice that yUnicorn is used as the y parameter for the image that draws the unicorn.

#4

Code Game Over

Make a condition (using an if statement) that determines game over if the unicorn falls out of the window, and write "game over" if it happens.

About if-statements:

The if-else statement helps control the flow of your code.

A condition is placed between the parenthesis following 'if', when that condition evalues to truthy, the code between the following curly braces is run. (https://p5js.org/reference/#/p5/if-else)

Tip:

The unicorn leaves the window when its y position is greater than the height of the window.

Use text("Game Over", x position, y position); to write "game over" on your window.

#5

Draw a moon and give it a color. Use the shape circle() and the function fill()

circle(x pos, y pos, diameter);

fill(r,g,b);

Parameters

r - red (from 0 to 255)

g - green (from 0 to 255)

b - blue (from 0 to 255)

#6

Make the moon move on the x axis.

Once again you need to make a variable that can be used to define the moon's X position. This variable needs to increase every time the draw method runs.

Make sure that if the value gets higher than the size of the window it will be set back to zero. In this way the moon will start its travel again, from the left side of the window. In the unicorn-world it's always night and always full moon ;-)

let xMoon = 0;

function draw(){

xMoon = xMoon + 2;

if(xMoon > width){  
 xMoon = 0;
}

}

Your game should look similar to this:

CONGRATULATIONS!

If you have made into here you are done with what we had in mind for today!

If you want to work further on the game you are welcome to try the following exercises (voluntary)

#7

Use Co2 emission data from energidataservice.dk to define the size of your ellipse

let jsonData;  
 let co2;

function preload() {  
  let url =
   'https://api.energidataservice.dk/dataset/CO2Emis?start=2024-08-19T05:00&end=2024-08-19T06:00&limit=1';
  jsonData = loadJSON(url); // OBS do NOT put this function in draw - bad and impolite to ask their server over the network 30 times a second!
}

function setup() {  
  createCanvas(600, 350);
}

function draw() {

  co2 = jsonData.records[0].CO2Emission;
  ellipse(width / 2, height / 2, co2, co2); 

}

#8

Make a collision detection between moon and flappy unicorn. You can use the function dist(), that calculates the distance between two points. Look up in references (https://p5js.org/reference) for how to use this function.

#9

Make a "state" variable that defines either there is game over or not. Here is the idea:

if(state == 1){

   //game runs;

   if(gameOver){
      state = 0;
   }

} else {

text("GameOver",x position, y position);

}

#10

"Restart" the game if the mouse is pressed: · Remember the state needs to be set to "running the game"

· The flappy unicorn needs to have its position within the window

· The moon needs to start from the left again.

#11

Make the background move, so it looks like the unicorn is moving. A way of doing it could be by having two copies of the background image moving in and out of the screen.

Code : Introduction to p5js

let backgroundImage;  
let unicornImage;  
let xMoon = 0;  
let yUnicorn = 0;

let url;  
let jsonData;  
let co2;

function preload() { 

  backgroundImage = loadImage("background.jpg");
  unicornImage = loadImage("unicorn.png");
  url =
   'https://api.energidataservice.dk/dataset/CO2Emis?start=2024-08-19T05:00&end=2024-08-19T06:00&limit=1';
  jsonData = loadJSON(url); 

}

function setup() {  

  createCanvas(600, 350);

}

function keyPressed() { 

  yUnicorn = yUnicorn - 30;

}

function draw() {

  //background
  image(backgroundImage, 0, 0, width, height);

  //unicorn
  yUnicorn = yUnicorn + 2;
  image(unicornImage, 300, yUnicorn, 35, 35);

  //moon
  xMoon = xMoon + 5;
  if (xMoon > width) {
    xMoon = 0;
  }

  co2 = jsonData.records[0].CO2Emission;
  fill(255, 255, 203);
  ellipse(xMoon, 50, co2, co2);

  //game over
  if (yUnicorn > height) {
    textAlign(CENTER);
    textSize(25);
    text("Game Over", width / 2, height / 2);
  }
}

Programming is a creative process. You are allowed to play around. You can try different things. The computer won't break.

More help:

https://p5js.org/reference/

https://p5js.org/learn/

https://learn.hobye.dk/development/p5js