Paddle.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. class Paddle {
  2. position = {x:10,y:10};
  3. size = {w:4, h:40};
  4. speed = 3;
  5. side = "left";
  6. score = 0;
  7. lastBallPosition = 0;
  8. constructor(side) {
  9. this.side = side;
  10. }
  11. init(game) {
  12. this.game = game;
  13. this.position.y = Math.floor((this.game.getHeight() - this.size.h) * Math.random());
  14. if(this.side == "left") {
  15. this.position.x = 10;
  16. } else if(this.side == "right") {
  17. this.position.x = this.game.getWidth() - 10 - this.size.w;
  18. }
  19. this.score = 0;
  20. }
  21. update(delta) {
  22. let targetPosition = this.game.getBallPosition();
  23. if(this.side == "right") {
  24. if(this.lastBallPosition > targetPosition.x) {
  25. this.lastBallPosition = targetPosition.x;
  26. return;
  27. }
  28. }
  29. if(this.side == "left") {
  30. if(this.lastBallPosition < targetPosition.x) {
  31. this.lastBallPosition = targetPosition.x;
  32. return;
  33. }
  34. }
  35. if(targetPosition.y > this.position.y + (this.size.h / 2)) {
  36. this.moveDown(delta);
  37. }
  38. if(targetPosition.y < this.position.y + (this.size.h / 2)) {
  39. this.moveUp(delta);
  40. }
  41. this.lastBallPosition = targetPosition.x;
  42. }
  43. moveDown(delta) {
  44. this.position.y += this.speed * delta;
  45. }
  46. moveUp(delta) {
  47. this.position.y -= this.speed * delta;
  48. }
  49. draw(context) {
  50. context.fillStyle = "#000000";
  51. context.beginPath();
  52. context.rect(this.position.x, this.position.y, this.size.w, this.size.h);
  53. context.fill();
  54. }
  55. collideSide(collisionBox) {
  56. let collisionSide = "";
  57. if(collisionBox.bottom < this.position.y + this.size.h &&
  58. collisionBox.top > this.position.y) {
  59. if(collisionBox.left < this.position.x + this.size.w &&
  60. collisionBox.right > this.position.x) {
  61. return this.side;
  62. }
  63. }
  64. return collisionSide;
  65. }
  66. getPosition() {
  67. return {x: this.position.x, y: this.position.y};
  68. }
  69. getHeightRatio() {
  70. return (this.position.y + (this.size.h / 2)) / this.game.getHeight();
  71. }
  72. getSize() {
  73. return {w:this.size.w, h:this.size.h};
  74. }
  75. addPoint() {
  76. this.score++;
  77. }
  78. getScore() {
  79. return this.score;
  80. }
  81. }