|
| 1 | +import { getPointer } from 'kontra'; |
| 2 | +import { PlayerControls } from './PlayerControls'; |
| 3 | +import { PointMass } from './PointMass'; |
| 4 | + |
| 5 | +export class Player { |
| 6 | + x; |
| 7 | + y; |
| 8 | + game; |
| 9 | + rope = []; // list of pointmasses |
| 10 | + pointMass; |
| 11 | + playerControls; |
| 12 | + |
| 13 | + constructor(x, y, game) { |
| 14 | + this.x = x; |
| 15 | + this.y = y; |
| 16 | + this.game = game; |
| 17 | + this.pointMass = new PointMass(x, y, { game, mass: 2 }); |
| 18 | + this.createTestRope(); |
| 19 | + this.playerControls = new PlayerControls(this); |
| 20 | + } |
| 21 | + |
| 22 | + hasRope() { |
| 23 | + return !!this.rope.length; |
| 24 | + } |
| 25 | + removeRope() { |
| 26 | + this.pointMass.removeLink(); |
| 27 | + this.rope.length = 0; |
| 28 | + } |
| 29 | + shootRope() { |
| 30 | + this.createTestRope(); |
| 31 | + } |
| 32 | + updateTestRope() { |
| 33 | + this.rope.forEach((p) => { |
| 34 | + p.update(); |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + renderTestRope(ctx) { |
| 39 | + this.rope.forEach((p) => { |
| 40 | + p.render(ctx); |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + createTestRope() { |
| 45 | + const anchor = new PointMass(this.game.canvas.width / 2, 100, { |
| 46 | + isAnchor: true, |
| 47 | + game: this.game, |
| 48 | + }); |
| 49 | + this.rope.push(anchor); |
| 50 | + for (let i = 1; i < 7; i++) { |
| 51 | + const p1 = this.rope[this.rope.length - 1]; |
| 52 | + const p2 = new PointMass(i * 10, i * 10, { game: this.game }); |
| 53 | + p1.attachTo(p2); |
| 54 | + this.rope.push(p2); |
| 55 | + } |
| 56 | + this.pointMass.attachTo(this.rope[this.rope.length - 1]); |
| 57 | + this.rope.push(this.pointMass); |
| 58 | + } |
| 59 | + |
| 60 | + dragTestRope() { |
| 61 | + if (this.game.isDragging && this.rope.length) { |
| 62 | + const pointer = getPointer(); |
| 63 | + const acnhorPoint = this.rope[this.rope.length - 1]; |
| 64 | + acnhorPoint.setPos(pointer.x, pointer.y); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + renderPlayer(ctx) { |
| 69 | + ctx.lineWidth = 2; |
| 70 | + |
| 71 | + ctx.beginPath(); |
| 72 | + ctx.arc(this.x, this.y, 5, 0, Math.PI * 2); |
| 73 | + ctx.stroke(); |
| 74 | + } |
| 75 | + |
| 76 | + applyForce(fX, fY) { |
| 77 | + this.pointMass.applyForce(fX, fY); |
| 78 | + } |
| 79 | + |
| 80 | + render(ctx) { |
| 81 | + this.renderTestRope(ctx); |
| 82 | + this.renderPlayer(ctx); |
| 83 | + } |
| 84 | + |
| 85 | + update() { |
| 86 | + this.x = this.pointMass.x; |
| 87 | + this.y = this.pointMass.y; |
| 88 | + this.updateTestRope(); |
| 89 | + this.dragTestRope(); |
| 90 | + this.playerControls.updateControls(); |
| 91 | + } |
| 92 | +} |
0 commit comments