xxxxxxxxxx
59
const NUMBER_OF_BOXES = 40
const BOX_SIZE = 50
class Ball {
constructor() {
this.x = 200
this.y = 200
this.diameter = 50
}
draw() {
fill('lemonchiffon')
circle(this.x, this.y, this.diameter)
}
}
class Box {
constructor() {
this.x = random(0, width - BOX_SIZE)
this.y = random(0, height - BOX_SIZE)
this.width = random(30, 50)
this.height = random(30, 50)
}
draw() {
fill(this.collidedWithBall() ? 'red' : 'white')
rect(this.x, this.y, this.width, this.height)
}
move() {
this.x -= 1
if (this.x < -this.width) {
this.x = width
this.y = random(0, height - BOX_SIZE)
}
}
collidedWithBall() {
return collideRectCircle(this.x, this.y, this.width,
this.height, ball.x, ball.y,
ball.diameter)
}
}
let ball = new Ball()
let boxes = []
function setup() {
createCanvas(400, 400);
while (boxes.length < NUMBER_OF_BOXES) {
boxes.push(new Box())
}
}
function draw() {
background('darkblue');
ball.draw()
for (let box of boxes) {
box.draw()
box.move()
}
}