xxxxxxxxxx
63
let balls = [];
function setup() {
createCanvas(400, 400);
// Create 10 Ball objects and push them into the array
for (let i = 0; i < 2; i++) {
let xPos = random(width); // Random x position
let yPos = random(height); // Random y position
let rAdius = random(10, 50); // Random radius
let xSpeed = random(-2, 5); // Random x speed
let ySpeed = random(-2, 5); // Random y speed
balls.push(new Ball(xPos, yPos, rAdius, xSpeed, ySpeed)); // Create new Ball
console.log(balls.length)
}
}
function draw() {
background(220);
// Balls array
for (let i = 0; i < balls.length; i++) {
balls[i].move(); // Move each ball
balls[i].bounce(); // Bounce each ball off the edges
balls[i].display(); // Display each ball
}
}
// define ball
class Ball {
constructor(xPos, yPos, rAdius, xSpeed, ySpeed) {
this.xPos = xPos;
this.yPos = yPos;
this.rAdius = rAdius;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}
// Move the ball by updating its position
move() {
this.xPos += this.xSpeed;
this.yPos += this.ySpeed;
}
// Bounce the ball off the edges of the canvas
bounce() {
if (this.xPos < 0 || this.xPos > width) {
this.xSpeed *= -1;
}
if (this.yPos < 0 || this.yPos > height) {
this.ySpeed *= -1;
}
}
// Display the ball on the canvas
display() {
ellipse(this.xPos, this.yPos, this.rAdius * 2);
}
}