Bouncing ball in P5.js

August 09, 2021



What is p5.js?

p5. js is a JavaScript library for creative coding, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else!*



Where can we code in p5.js?

We can use the p5.js free editor at this link



The basics of p5.js?

P5.js has 2 main built-in functions: setup() and draw(). They are represented as it follows.



function setup() { 

}

function draw() {

}



The setup() function is called only once.

The draw() function is called over and over again until the program is manually stopped. 



How can we program a bouncing ball in p5.js?

Step 1:
Create a 400x400 pixels canvas in the setup function. 

function setup() { 

    createCanvas(400, 400);

}


Step 2: Define the initial positions of the ball by declaring 2 variables before the setup function. 



let x=200;

let y=0;
 



function setup() { 

    createCanvas(400, 400);

}


Step 3: Draw your background in the draw function and create black a circle of 30 pixels radius at the positions defined in Step 2.

let x=200;

let y=0;
 



function setup() { 

    createCanvas(400, 400);

}



function draw(){

    background(220);

    fill(0);

    ellipse(x, y, 30);

}



Step 4: Declare a variable to control the speed of the ball along the vertical and change the y position of the ball in the draw function by the speed you defined. 

let x=200;

let y=0;
 

let yspeed=10; 



function setup() { 

    createCanvas(400, 400);

}

function draw(){

    background(220);

    fill(0);

    ellipse(x, y, 30);

    y=y+yspeed;

}



Step 5: Check if the ball is touching the upper or lower boundaries of your canvas and change its direction by adding a negative sign to the speed variable. 

let x=200;

let y=0;
 

let yspeed=10; 



function setup() { 

    createCanvas(400, 400);

}



function draw(){

    background(220);

    fill(0);

    ellipse(x, y, 30);

    y=y+yspeed;

    if(y>height || y<0) {

         yspeed = -yspeed; 

    }

}



https://p5js.org