// ---------------------------- // Parent class (or superclass) // ---------------------------- class Circle { constructor(x = 50, y = 50, r = 100, col = '#f00') { this.x = x; this.y = y; this.r = r; this.col = col; this.vx = random(-5,5); this.vy = random(-5,5); } move() { this.x += this.vx; this.y += this.vy; return this; } draw() { fill(this.col); ellipse(this.x,this.y,this.r); return this; // allows method chaining } } // ---------------------------- // Child class (or subclass) // ---------------------------- class BouncingCircle extends Circle { constructor(x = 50, y = 50, r = 50, col = '#0f0') { super(x, y, r, col); } move() { this.x += this.vx; this.y += this.vy; // reverse direction ('bounce') if(!this.onScreen()) { this.vx *= -1; this.vy *= -1; } return this; // allows method chaining } onScreen() { if(this.x - (this.r / 2) < 0 || this.x + (this.r / 2) > width || this.y - (this.r / 2) < 0 || this.y + (this.r / 2) > height) { return false; } return true; }; } // ------------------------------- // Code to use the above 'classes' // ------------------------------- let circles = []; function setup() { createCanvas(400,400); background(0); } function draw() { background(0); for(let i = 0; i < circles.length; i++) { circles[i].move().draw(); // method chaining } } function mousePressed() { // clicking on the left half of the screen creates bouncing circles if(mouseX > width / 2) { circles.push( new BouncingCircle(mouseX, mouseY) ); } else { circles.push( new Circle(mouseX, mouseY) ); } }