class Ball { position = {x:15, y: 20}; radius = 5; game = null; velocity = {x:3, y:2.3}; isAlive = true; constructor() { } init(game) { this.game = game; this.position.x = Math.floor(this.game.getWidth() * Math.random()); this.position.y = Math.floor(this.game.getHeight() * Math.random()); this.velocity.x = Math.floor(6 * Math.random() - 3) || 1; this.velocity.y = Math.floor(6 * Math.random() - 3) || 1; this.isAlive = true; } update(delta) { this.position.x += delta * this.velocity.x; this.position.y += delta * this.velocity.y; let collisionBox = { left: this.position.x - this.radius, top: this.position.y - this.radius, right: this.position.x + this.radius, bottom: this.position.y + this.radius }; this.handleBorderCollision(collisionBox); this.handlePaddleCollision(collisionBox); } handleBorderCollision(collisionBox) { switch(this.game.collideSide(collisionBox)) { case "top": this.velocity.y *= -1 this.position.y = this.radius; break; case "left": this.game.getPaddle("right").addPoint(); this.setDead(); break; case "bottom": this.velocity.y *= -1 this.position.y = this.game.getHeight() - this.radius; break; case "right": this.game.getPaddle("left").addPoint(); this.setDead(); break; default: break; } } handlePaddleCollision(collisionBox) { let leftPaddle = this.game.getPaddle("left"); switch(leftPaddle.collideSide(collisionBox)) { case "left": this.velocity.x *= -1; this.position.x = leftPaddle.getPosition().x + leftPaddle.getSize().w + this.radius; break; default: break; } let rightPaddle = this.game.getPaddle("right"); switch(rightPaddle.collideSide(collisionBox)) { case "right": this.velocity.x *= -1; this.position.x = rightPaddle.getPosition().x - this.radius; break; default: break; } } setDead() { this.isAlive = false; } isDead() { return !this.isAlive; } draw(context) { context.fillStyle = "#000000"; context.beginPath(); context.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI); context.fill(); } getBallPositionRatio() { return (this.position.y + this.radius) / this.game.getHeight(); } }