Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
P5.js example demonstrating ES6 classes, inheritance and method chaining
// ----------------------------
// 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) );
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>p5.js playground</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/addons/p5.sound.min.js"></script>
<script src="script.js"></script>
<style>
body {
margin:0;
padding:0;
overflow: hidden;
}
canvas {
margin:auto;
}
</style>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.