xxxxxxxxxx
55
let balls = []; // Array to store the ball objects
function setup() {
createCanvas(400, 400);
// Create a few ball objects and add them to the array
for (let i = 0; i < 5; i++) {
let ball = new Ball(random(width), random(height), random(20, 40));
balls.push(ball);
}
}
function draw() {
background(220);
// Update and display each ball
for (let i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].display();
}
}
// Ball class definition
class Ball {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
this.xSpeed = random(1, 10); // Horizontal speed
this.ySpeed = random(1, 20); // Vertical speed
this.color = color(random(255), random(255), random(255));
}
move() {
// Update the ball's position based on its speed
this.x += this.xSpeed;
this.y += this.ySpeed;
// Bounce off the canvas edges
if (this.x < 0 || this.x > width) {
this.xSpeed *= -1;
}
if (this.y < 0 || this.y > height) {
this.ySpeed *= -1;
}
}
display() {
// Draw the ball
fill(this.color);
noStroke();
ellipse(this.x, this.y, this.radius * 2);
}
}