let brick;
let bricks = [];
function setup() {
createCanvas(600, 400);
brick = new Brick(300, 350, 10, 50);
ball = new Ball();
//create bricks 12x6
for (i = 0; i < 12; i++) {
bricks[i] = [];
for (j = 0; j < 6; j++) {
bricks[i][j] = new Brick(i * 50, j * 30, 20, 40);
}
}
}
function draw() {
background(255);
fill(255);
brick.show();
brick.move();
ball.move();
ball.show();
//check for collision and change direction between the main brick and the ball
if (ball.hits(brick)) {
ball.yspeed = -3
}
// display the bricks
for (i = 0; i < 12; i++) {
for (j = 0; j < bricks[i].length; j++) {
bricks[i][j].show();
// remove bricks
if (ball.hits(bricks[i][j])) {
ball.yspeed = 3;
bricks[i].splice(j, 1);
console.log(bricks)
}
}
}
}
class Brick {
constructor(x = 300, y = 350, h = 30, w = 50) {
this.x = x;
this.y = y;
this.h = h;
this.w = w;
}
show() {
rect(this.x, this.y, this.w, this.h);
}
// main brick movement
move() {
if (this.x > 0) {
if (keyIsDown(LEFT_ARROW)) {
this.x -= 10;
}
}
if (this.x < width - 50) {
if (keyIsDown(RIGHT_ARROW)) {
this.x += 10;
}
}
}
}
class Ball {
constructor(x = 300, y = 250, r = 10, xspeed = 3, yspeed = 3) {
this.x = x;
this.y = y;
this.r = r;
this.xspeed = xspeed;
this.yspeed = yspeed;
}
show() {
fill(0)
ellipse(this.x, this.y, this.r);
}
// check the position of the ball if it's withing boundaries
move() {
// if it leaves the width, change direction
if (this.x > width) {
this.xspeed = -this.xspeed;
}
else if (this.x < 0) {
this.xspeed = Math.abs(this.xspeed);
}
//if it leaves the height, change direction
if (this.y > height + 50) {
return true;
}
if (this.y < 0) {
this.yspeed = Math.abs(this.yspeed)
}
this.x += this.xspeed;
this.y += this.yspeed;
}
hits(brick) {
// check if the circle is intersecting with the brick, still need to test if the ball is inside the brick
if(this.x + this.r > brick.x &&
this.x - this.r < (brick.x + brick.w) &&
this.y + this.r > brick.y &&
this.y - this.r < (brick.y + brick.h))
{
return true;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>