xxxxxxxxxx
69
let ballA;
let ballB;
function setup() {
createCanvas(400, 400);
noStroke();
ballA = new Ball(random(width),random(height));
ballB = new Ball(random(width),random(height))
}
function draw() {
background(220);
ballA.display();
ballA.move();
ballA.bounce();
ballA.changeColor();
ballB.display();
ballB.move();
ballB.bounce();
ballB.changeColor();
}
// _______________Class: Ball
class Ball {
// constructor
constructor(x, y) {
this.x = x;
this.y = y;
this.dia = random(50, 100);
this.xSpd = random(-10, 5);
this.ySpd = random(-2, 2);
}
// ---------- ball class methods
// move
move() {
this.x += this.xSpd;
this.y += this.ySpd;
}
// bounce
bounce() {
if (this.x < 0 || this.x > width) {
this.xSpd = this.xSpd * -1;
}
if (this.y < 0 || this.y > width) {
this.ySpd = this.ySpd * -1;
}
}
// change color
changeColor() {
if (this.x < 0 || this.x > width) {
fill(random(255), random(255), random(255));
if (this.y < 0 || this.y > height) {
fill(random(255), random(255), random(255));
}
}
}
// displays balls
display() {
ellipse(this.x, this.y, this.dia, this.dia);
}
}