| 1 | class GameObject |
| 2 | { |
| 3 | transform = null; |
| 4 | renderer = null; |
| 5 | collider = null; |
| 6 | scene = null; |
| 7 | _layer = 0; |
| 8 | tags = []; |
| 9 | |
| 10 | destroyed = false; |
| 11 | |
| 12 | constructor (x, y, sprite, layer = 0) |
| 13 | { |
| 14 | this.transform = new Transform(this, x, y, 1, 1, 0); |
| 15 | this.renderer = new Renderer(this, sprite); |
| 16 | this.collider = new Collider(this); |
| 17 | this._layer = layer; |
| 18 | } |
| 19 | |
| 20 | get layer () |
| 21 | { |
| 22 | return this._layer; |
| 23 | } |
| 24 | |
| 25 | set layer (value) |
| 26 | { |
| 27 | if (this._layer === value) |
| 28 | { return; } |
| 29 | this._layer = value; |
| 30 | if (this.scene) |
| 31 | { this.scene.objectLayerChanged(this); } |
| 32 | } |
| 33 | |
| 34 | initQuadtree (quadTree) |
| 35 | { |
| 36 | this.quadTree = quadTree; |
| 37 | } |
| 38 | |
| 39 | checkQuadtree () |
| 40 | { |
| 41 | if (!this.quadTree) |
| 42 | { return; } |
| 43 | |
| 44 | const x = this.transform.position.x; |
| 45 | const y = this.transform.position.y; |
| 46 | // Skip reinsert when the object has not moved since the last check. |
| 47 | if (this.node && this._qtX === x && this._qtY === y) |
| 48 | { return; } |
| 49 | this._qtX = x; |
| 50 | this._qtY = y; |
| 51 | |
| 52 | if (this.node) |
| 53 | { |
| 54 | if (x < this.node.x1 |
| 55 | || x > this.node.x2 |
| 56 | || y < this.node.y1 |
| 57 | || y > this.node.y2) |
| 58 | { |
| 59 | this.quadTree.remove(this); |
| 60 | this.quadTree.add(this); |
| 61 | } |
| 62 | } |
| 63 | else |
| 64 | { |
| 65 | this.quadTree.add(this); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | update (deltaTime) |
| 70 | { |
| 71 | if (this.destroyed) |
| 72 | { return; } |
| 73 | |
| 74 | this.transform.update(deltaTime); |
| 75 | this.collider.update(deltaTime); |
| 76 | this.renderer.update(deltaTime); |
| 77 | |
| 78 | this.checkQuadtree(); |
| 79 | } |
| 80 | |
| 81 | destroy () |
| 82 | { |
| 83 | if (!this.destroyed) |
| 84 | { |
| 85 | this.onDestroy && this.onDestroy(); |
| 86 | this.quadTree && this.quadTree.remove(this); |
| 87 | this.scene && this.scene.removeObject(this); |
| 88 | this.destroyed = true; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | draw () |
| 93 | { |
| 94 | if (this.destroyed) |
| 95 | { return; } |
| 96 | |
| 97 | this.renderer.draw(); |
| 98 | } |
| 99 | } |