123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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();
- }
- }
|