Ball.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. class Ball {
  2. position = {x:15, y: 20};
  3. radius = 5;
  4. game = null;
  5. velocity = {x:3, y:2.3};
  6. isAlive = true;
  7. constructor() {
  8. }
  9. init(game) {
  10. this.game = game;
  11. this.position.x = Math.floor(this.game.getWidth() * Math.random());
  12. this.position.y = Math.floor(this.game.getHeight() * Math.random());
  13. this.velocity.x = Math.floor(6 * Math.random() - 3) || 1;
  14. this.velocity.y = Math.floor(6 * Math.random() - 3) || 1;
  15. this.isAlive = true;
  16. }
  17. update(delta) {
  18. this.position.x += delta * this.velocity.x;
  19. this.position.y += delta * this.velocity.y;
  20. let collisionBox = {
  21. left: this.position.x - this.radius,
  22. top: this.position.y - this.radius,
  23. right: this.position.x + this.radius,
  24. bottom: this.position.y + this.radius
  25. };
  26. this.handleBorderCollision(collisionBox);
  27. this.handlePaddleCollision(collisionBox);
  28. }
  29. handleBorderCollision(collisionBox) {
  30. switch(this.game.collideSide(collisionBox)) {
  31. case "top":
  32. this.velocity.y *= -1
  33. this.position.y = this.radius;
  34. break;
  35. case "left":
  36. this.game.getPaddle("right").addPoint();
  37. this.setDead();
  38. break;
  39. case "bottom":
  40. this.velocity.y *= -1
  41. this.position.y = this.game.getHeight() - this.radius;
  42. break;
  43. case "right":
  44. this.game.getPaddle("left").addPoint();
  45. this.setDead();
  46. break;
  47. default:
  48. break;
  49. }
  50. }
  51. handlePaddleCollision(collisionBox) {
  52. let leftPaddle = this.game.getPaddle("left");
  53. switch(leftPaddle.collideSide(collisionBox)) {
  54. case "left":
  55. this.velocity.x *= -1;
  56. this.position.x = leftPaddle.getPosition().x + leftPaddle.getSize().w + this.radius;
  57. break;
  58. default:
  59. break;
  60. }
  61. let rightPaddle = this.game.getPaddle("right");
  62. switch(rightPaddle.collideSide(collisionBox)) {
  63. case "right":
  64. this.velocity.x *= -1;
  65. this.position.x = rightPaddle.getPosition().x - this.radius;
  66. break;
  67. default:
  68. break;
  69. }
  70. }
  71. setDead() {
  72. this.isAlive = false;
  73. }
  74. isDead() {
  75. return !this.isAlive;
  76. }
  77. draw(context) {
  78. context.fillStyle = "#000000";
  79. context.beginPath();
  80. context.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
  81. context.fill();
  82. }
  83. getBallPositionRatio() {
  84. return (this.position.y + this.radius) / this.game.getHeight();
  85. }
  86. }