xxxxxxxxxx
70
class BouncingBall {
constructor(xSpeed0, ySpeed0, id) {
this.xPos = random(width);
this.yPos = random(height);
this.xSpeed = xSpeed0;
this.ySpeed = ySpeed0;
this.id = id; // each ball gets a unique ID
this.offset = 0;
this.alive = true;
}
move() {
// move the ball
this.xPos += this.xSpeed;
this.offset += 0.01;
this.yPos += this.ySpeed;
}
checkForCollisions() {
// check first for left and right wall
if (this.xPos <= -15 || this.xPos >= width + 15) {
this.alive = false;
}
// do the same for the ceiling and the floor
if (this.yPos <= -15 || this.yPos >= height + 15) {
this.alive = false;
}
}
draw() {
circle(this.xPos, this.yPos, 30);
}
}
let ball = [];
let quantity = 10;
function setup() {
createCanvas(400, 400);
frameRate(20);
for (let i = 0; i < quantity; i++) {
// For debugging, each ball gets an ID which is its initial position
// in the array
ball.push(new BouncingBall(random(-5, 5), random(-5, 5), i));
}
}
function draw() {
background(240);
for (let i = ball.length - 1; i >= 0; i--) {
ball[i].move();
ball[i].checkForCollisions();
ball[i].draw();
// If a ball has left the canvas,
// delete it
if (!ball[i].alive) {
print("Ball ID " + ball[i].id + " is not alive, will remove it");
ball.pop(i);
// for debugging, print out the IDs of all remaining balls
print("Ball IDs after removing: ");
for (let i = ball.length - 1; i >= 0; print(ball[i--].id));
}
}
}