xxxxxxxxxx
52
let balls = []; // store multiple balls
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 100; i++) {
// create 100 balls
let diameter = random(20, 50);
let col = color(random(255), random(255), random(255));
let ball = new Ball(random(width), random(height), diameter, col);
balls.push(ball);
}
}
function draw() {
background(0);
for (let i = 0; i < balls.length; i++) {
balls[i].display();
balls[i].move();
balls[i].checkEdges(); // check if each ball has reached the edges of the canvas
}
}
class Ball {
constructor(x, y, diameter, col) {
this.x = x;
this.y = y;
this.diameter = diameter;
this.col = col;
this.speedX = random(-3, 3);
this.speedY = random(-3, 3);
}
display() {
fill(this.col);
ellipse(this.x, this.y, this.diameter, this.diameter);
}
move() {
this.x += this.speedX;
this.y += this.speedY;
}
checkEdges() {
if (this.x <= 0 || this.x >= width) {
this.speedX *= -1;
}
if (this.y <= 0 || this.y >= height) {
this.speedY *= -1;
}
}
}