xxxxxxxxxx
77
function setup() {
createCanvas(400, 400);
ball = new PongBall(
random(width),
random(height),
random([true, false]),
random([true, false])
);
}
function draw() {
background(237, 187, 29);
fill(random(255), random(255), random(255));
ball.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("gif", 5);
}
if (key === "n") {
delete ball;
ball = new PongBall(
random(width),
random(height),
random([true, false]),
random([true, false])
);
}
}