xxxxxxxxxx
72
/*
* Creative Coding Workshop #4 Demo - Multiple Randomly-Colored Bouncing Faces in an Array
*
* Jack B. Du (github@jackbdu.com)
*/
// a class (template/blueprint) for face
class Face {
// constructor for initializing the object with these provided parameters
constructor(x, y, d) {
this.d = d;
this.pos = createVector(x, y);
this.v = createVector(random(-1,1),
random(-1,1));
// assign a random color
this.c = color(random(255),
random(255),
random(255));
}
// chech if touching edges
checkEdges() {
// check left and right edges
if (this.pos.x < this.d/2 ||
this.pos.x > width - this.d/2) {
this.v.x = this.v.x * -1;
}
// check top and bottom edges
if (this.pos.y < this.d/2 ||
this.pos.y > height - this.d/2) {
this.v.y = this.v.y * -1;
}
}
// move face by adding velocity
move() {
this.pos.add(this.v);
}
// display current face with specified color
display() {
fill(this.c);
strokeWeight(3);
circle(this.pos.x,this.pos.y,this.d);
circle(this.pos.x-this.d/5,this.pos.y-this.d/10,this.d/4);
circle(this.pos.x+this.d/5,this.pos.y-this.d/10,this.d/4);
}
}
let faces = [];
function setup() {
createCanvas(400, 400);
// repeat 100 times
for (let i = 0; i < 100; i++) {
// create and add a face object to the array
// specify a random location and a random diameter
faces.push(new Face(random(100, 300),
random(100, 300),
random(50,100)));
}
}
function draw() {
background(220);
// iterate through all faces
for (let f of faces) {
f.checkEdges();
f.move();
f.display();
}
}