xxxxxxxxxx
70
// Example: OOP and Bouncing Ball
// Sept. 13 2022
let ball1;
let ball2;
let ball = [];
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
ball[i] = new BouncingBall(i + 2, 10);
}
// ball1 = new BouncingBall(4, 3);
// ball2 = new BouncingBall(8, 10);
}
function draw() {
background(220);
for (let i = 0; i < 10; i++) {
ball[i].move();
ball[i].checkForCollisions();
ball[i].display();
}
// ball1.move();
// ball1.checkForCollisions();
// ball1.display();
// ball2.move();
// ball2.checkForCollisions();
// ball2.display();
}
class BouncingBall {
constructor(xSpeed0, ySpeed0) {
this.xPos = width / 2;
this.yPos = random(100, 300);
this.xSpeed = xSpeed0;
this.ySpeed = ySpeed0;
this.diameter = 30;
this.radius = 15;
}
move() {
//move ball
this.xPos += this.xSpeed;
this.yPos += this.ySpeed;
}
checkForCollisions() {
//check first for left and right wall
if (this.xPos <= this.radius || this.xPos >= width - this.radius) {
this.xSpeed = -this.xSpeed;
}
//do the same for the ceiling and the floor
if (this.yPos <= this.radius || this.yPos >= width - this.radius) {
this.ySpeed = -this.ySpeed;
}
}
display() {
circle(this.xPos, this.yPos, this.diameter);
}
}