123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- class Paddle {
- position = {x:10,y:10};
- size = {w:4, h:40};
- speed = 3;
- side = "left";
- score = 0;
- lastBallPosition = 0;
- constructor(side) {
- this.side = side;
- }
- init(game) {
- this.game = game;
- this.position.y = Math.floor((this.game.getHeight() - this.size.h) * Math.random());
- if(this.side == "left") {
- this.position.x = 10;
- } else if(this.side == "right") {
- this.position.x = this.game.getWidth() - 10 - this.size.w;
- }
- this.score = 0;
- }
- update(delta) {
- let targetPosition = this.game.getBallPosition();
- if(this.side == "right") {
- if(this.lastBallPosition > targetPosition.x) {
- this.lastBallPosition = targetPosition.x;
- return;
- }
- }
- if(this.side == "left") {
- if(this.lastBallPosition < targetPosition.x) {
- this.lastBallPosition = targetPosition.x;
- return;
- }
- }
- if(targetPosition.y > this.position.y + (this.size.h / 2)) {
- this.moveDown(delta);
- }
- if(targetPosition.y < this.position.y + (this.size.h / 2)) {
- this.moveUp(delta);
- }
- this.lastBallPosition = targetPosition.x;
- }
- moveDown(delta) {
- this.position.y += this.speed * delta;
- }
- moveUp(delta) {
- this.position.y -= this.speed * delta;
- }
- draw(context) {
- context.fillStyle = "#000000";
- context.beginPath();
- context.rect(this.position.x, this.position.y, this.size.w, this.size.h);
- context.fill();
- }
- collideSide(collisionBox) {
- let collisionSide = "";
- if(collisionBox.bottom < this.position.y + this.size.h &&
- collisionBox.top > this.position.y) {
- if(collisionBox.left < this.position.x + this.size.w &&
- collisionBox.right > this.position.x) {
- return this.side;
- }
- }
- return collisionSide;
- }
- getPosition() {
- return {x: this.position.x, y: this.position.y};
- }
- getHeightRatio() {
- return (this.position.y + (this.size.h / 2)) / this.game.getHeight();
- }
- getSize() {
- return {w:this.size.w, h:this.size.h};
- }
- addPoint() {
- this.score++;
- }
- getScore() {
- return this.score;
- }
- }
|