xxxxxxxxxx
59
let balls = [];
function setup() {
createCanvas(400, 400);
for (let b = 0; b < 2; b++) {
balls.push(
new Ball(random(width), random(height), random(-5, 5), random(-3, 3), false)
);
}
}
function draw() {
background(220);
for (let ball of balls) {
ball.move();
ball.bounce();
ball.display();
}
}
// Define Ball class
class Ball {
constructor(x, y, xspeed, yspeed, followMouse) {
this.x = x;
this.y = y;
this.xspeed = xspeed;
this.yspeed = yspeed;
this.followMouse = followMouse;
}
move() {
if (this.followMouse) {
// Move a small move of the distance towards the mouse
this.x += (mouseX - this.x) * 0.01;
this.y += (mouseY - this.y) * 0.01;
} else {
this.x += this.xspeed;
this.y += this.yspeed;
}
}
bounce() {
if (this.x < 0 || this.x > width) {
this.xspeed *= -1;
}
if (this.y < 0 || this.y > height) {
this.yspeed *= -1;
}
}
display() {
ellipse(this.x, this.y, 50, 50);
}
}
function mousePressed() {
balls.push(new Ball(mouseX, mouseY, 0, 0, true)); //
}