xxxxxxxxxx
68
//Inspired by The Coding Train:
//https://www.youtube.com/watch?v=T-HGdc8L-7w&list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA&index=24
let balls = [];
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
//BALLS
for (let i = 0; i < balls.length; i++) {
balls[i].rollover(mouseX, mouseY);
balls[i].show();
balls[i].move(); //update position
}
//TITLE
fill(0);
textSize(24);
textAlign(CENTER);
text("Click empty space to add balls!", width / 2, 50);
text("Left-click a ball to clone it!", width / 2, 75);
text("Right-click a ball to remove it!", width / 2, 100);
}
function mousePressed() {
let hits = [];
//in hits, store indices of balls hit by click
for (let i = 0; i < balls.length; i++) {
if (balls[i].isCover(mouseX, mouseY)) {
hits.push(i);
}
}
//if there are hits, clone or remove depending on button
if (hits.length > 0) {
if (mouseButton === LEFT) {
for (let i = 0; i < hits.length; i++) {
balls.push(balls[hits[i]].clone());
}
}
else if (mouseButton === RIGHT) {
//loop backwards since, e.g.
//removing b from [a, b, c] changes index of c
//but doesn't change index of a
for (let i = hits.length - 1; i >= 0; i--) {
balls.splice(hits[i], 1);
}
}
}
//else, create new ball
else {
let r, g, b, a, ballFill;
r = random(0, 255);
g = random(0, 255);
b = random(0, 255);
a = random(0, 255);
ballFill = color(r, g, b, a);
balls.push(new Ball(ballFill, mouseX, mouseY));
}
}