xxxxxxxxxx
55
// Declares a variable and initializes it as an empty array
let circles = [];
function setup() {
createCanvas(600, 600);
}
function draw() {
background(220);
// generate circles on mouse click
if (mouseIsPressed) {
// create a circle
let newCircle = {
x: mouseX,
y: mouseY,
diameter: random(10, 50),
speedX: random(-2, 2),
speedY: random(-2, 2),
// Generate random color
r: random(255),
g: random(255),
b: random(255)
};
// Newly created circle object is added to the circles array
circles.push(newCircle);
}
// This for loop iterates over each circle object stored in the circles array and updates its position
for (let i = 0; i < circles.length; i++) {
circles[i].x += circles[i].speedX;
circles[i].y += circles[i].speedY;
// Bounce off walls
if (circles[i].x <= 0 || circles[i].x >= width) {
circles[i].speedX *= -1;
}
if (circles[i].y <= 0 || circles[i].y >= height) {
circles[i].speedY *= -1;
}
// Set fill color
fill(circles[i].r, circles[i].g, circles[i].b);
// Draw circle
ellipse(circles[i].x, circles[i].y, circles[i].diameter);
}
}
function keyPressed() {
// Clear the circles array when the 'c' key is pressed
if (key === 'c' || key === 'C') {
circles = [];
}
}