xxxxxxxxxx
131
var wall1, wall2;
var ball;
function keyPressed() {
if (keyCode === UP_ARROW) {
wall1.y = wall1.y - 80;
}
if (keyCode === DOWN_ARROW) {
wall1.y = wall1.y + 80;
}
}
function setup() {
createCanvas(650, 500);
wall1 = new Wall(20, 20, 20, 120);
wall2 = new Wall(width - 40, 20, 20, 120);
ball = new Ball(width / 2, height / 2, 20);
paddles = [wall1, wall2];
}
function draw() {
background(0);
let aSq = wall1.b * ball.h;
let aCr = PI * ball.r * ball.r;
let d = dist(ball.x, wall1.x, ball.r, wall1.x / 2);
if (d < ball.r + wall1.x / 2) {
Ball.xspeed = Ball.xspeed * -1;
Ball.yspeed = Ball.yspeed * -1;
}
ball.moveBall();
ball.showBall();
//wall1.moveSquare();
wall1.showSquare();
wall2.moveSquare();
wall2.showSquare();
}
class Ball {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
this.xspeed = random(5, 6);
this.yspeed = random(5, 6);
}
worldCollision() {
if (this.x + this.r >= width) {
this.x = width - this.r; // move back to 'within bounds'
this.xspeed = this.xspeed * -1; // flip dir
}
if (this.x - this.r <= 0) {
this.x = 0 + this.r;
this.xspeed = this.xspeed * -1;
}
if (this.y + this.r >= height) {
this.y = height - this.r;
this.yspeed = this.yspeed * -1;
}
if (this.y - this.r <= 0) {
this.y = 0 + this.r;
this.yspeed = this.yspeed * -1;
}
}
paddleCollision() {
for (let paddle of paddles) {
if (this.x >= paddle.x && this.x <= (paddle.x + paddle.b) &&
this.y >= paddle.y && this.y <= (paddle.y + paddle.h)) {
this.xspeed = this.xspeed * -1;
this.yspeed = (this.y - (paddle.y + paddle.h / 2)) / 10;
}
}
}
showBall() {
stroke(255);
strokeWeight(4);
noFill();
ellipse(this.x, this.y, this.r * 2);
}
moveBall() {
this.worldCollision();
this.paddleCollision();
this.x = this.x + this.xspeed;
this.y = this.y + this.yspeed;
}
}
class Wall {
constructor(x, y, b, h) {
this.x = x;
this.y = y;
this.b = b;
this.h = h;
this.yspeed = random(5, 8);
}
showSquare() {
rect(this.x, this.y, this.b, this.h);
}
moveSquare() {
if (this.y >= height - this.h || this.y <= 0) {
this.yspeed = this.yspeed * -1;
}
this.y = this.y + this.yspeed;
}
}