Skip to content

Instantly share code, notes, and snippets.

@s-estay
Created August 23, 2018 10:14
Show Gist options
  • Save s-estay/b7ede5d09bab23afbd92ab1ab55ae7a9 to your computer and use it in GitHub Desktop.
Save s-estay/b7ede5d09bab23afbd92ab1ab55ae7a9 to your computer and use it in GitHub Desktop.
Trying out classes in P5js
let bubble1, bubble2; //global variables
function setup(){
createCanvas(640, 200);
bubble1 = new Bubble(320, 50, 20, 'red', 2); //start at the center of the canvas
bubble2 = new Bubble(160, 50, 10, 'blue', 1); //new bubble2 to the left of bubble1
//print(bubble.x, bubble.y);
}
function draw(){
background(0);
bubble1.move();
bubble1.bounce();
bubble1.show();
bubble2.move();
bubble2.bounce();
bubble2.show();
}
class Bubble {
constructor(_x, _y, _r, _c, _s){ //object initial setup (object template)
this.x = _x; //this: refers to the current object (this dot)
this.y = _y; //(x, y): starting location
this.r = _r; //bubble´s radius
this.c = _c; //bubble´s colour
this.vx = _s * 2; //bubble´s speed in the x-axis
this.vy = _s * -1; //bubble´s speed in the y-axis
}
move(){
this.x = this.x + this.vx;
this.y = this.y + this.vy;
}
bounce(){
if(this.x > width || this.x < 0){
this.vx = this.vx * -1;
}
if(this.y > height || this.y < 0){
this.vy = this.vy * -1;
}
}
show(){
stroke(255);
strokeWeight(4);
fill(this.c);
ellipse(this.x, this.y, this.r*2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment