xxxxxxxxxx
67
let balls = [];
function setup() {
createCanvas(200, 200);
for (let i = 0; i < 20; i++) {
balls.push(new PongBall(random(width),random(height),random([true,false]),random([true,false])));
}
}
function draw() {
background("rgb(18,5,121)");
for (let i = 0; i < balls.length; i++) {
fill(random(["#A30000","#FFF900","#FF6B00"]))
balls[i].drawBall();
}
}
class PongBall {
constructor(x, y, dirX, dirY) {
this.x = x;
this.y = y;
this.dirX = dirX;
this.dirY = dirY;
}
bounce() {
if (this.dirX == true) {
this.x = this.x + 20;
} else {
this.x = this.x - 20;
}
if (this.dirY == true) {
this.y = this.y + 20;
} else {
this.y = this.y - 20;
}
}
update() {
if (this.x <= 0 || this.x >= width) {
if (this.dirX == true) {
this.dirX = false;
} else {
this.dirX = true;
}
}
if (this.y <= 0 || this.y >= height) {
if (this.dirY == true) {
this.dirY = false;
} else {
this.dirY = true;
}
}
}
drawBall() {
this.update();
this.bounce();
circle(this.x, this.y, 30);
}
}
function keyPressed() {
if (key == "s") {
saveGif("object-array", 5);
}
}