|
| 1 | +import { system, world } from 'mojang-minecraft'; |
| 2 | +class TickEvent { |
| 3 | + constructor() { |
| 4 | + this.subscriptions = {}; |
| 5 | + this.lastTickDate; |
| 6 | + this.deltaTime; |
| 7 | + this.currentTick = 0; |
| 8 | + this.tickCheck; |
| 9 | + this.avgDeltaTime = []; |
| 10 | + this.tps; |
| 11 | + } |
| 12 | + __checkTicks() { |
| 13 | + if (this.tickCheck) return; |
| 14 | + this.tickCheck = () => { |
| 15 | + const { lastTickDate = (new Date()).getTime() } = this; |
| 16 | + this.currentTick++; |
| 17 | + this.deltaTime = (new Date()).getTime() - lastTickDate; |
| 18 | + this.avgDeltaTime.push(this.deltaTime); |
| 19 | + if (this.avgDeltaTime.length > 100) this.avgDeltaTime.shift(); |
| 20 | + const { avgDeltaTime } = this; |
| 21 | + this.tps = Math.round((1 / (avgDeltaTime.reduce((t, c) => t + c) / avgDeltaTime.length / 1000)) * 10) / 10; |
| 22 | + this.lastTickDate = (new Date()).getTime(); |
| 23 | + system.run(this.tickCheck); |
| 24 | + }; |
| 25 | + system.run(this.tickCheck); |
| 26 | + } |
| 27 | + /** |
| 28 | + * @method subscribe |
| 29 | + * @param {String} key |
| 30 | + * @param {Function} callback |
| 31 | + */ |
| 32 | + subscribe(key, callback) { |
| 33 | + this.__checkTicks(); |
| 34 | + this.subscriptions[key] = () => { |
| 35 | + const { deltaTime = 0, currentTick = 0, tps = 20 } = this; |
| 36 | + callback({ deltaTime, currentTick, tps }); |
| 37 | + system.run(this.subscriptions[key]); |
| 38 | + }; |
| 39 | + system.run(this.subscriptions[key]); |
| 40 | + } |
| 41 | + /** |
| 42 | + * @method unsubscribe |
| 43 | + * @param {String} key |
| 44 | + */ |
| 45 | + unsubscribe(key) { |
| 46 | + |
| 47 | + console.warn(Object.keys(this.subscriptions).length); |
| 48 | + if (Object.keys(this.subscriptions).length <= 1) { |
| 49 | + system.run(() => { this.__checkTicks = false; }); |
| 50 | + } |
| 51 | + this.subscriptions[key] = () => { }; |
| 52 | + |
| 53 | + system.run(() => { |
| 54 | + delete this.subscriptions[key]; |
| 55 | + }); |
| 56 | + } |
| 57 | +} |
| 58 | +export const tickEvent = new TickEvent(); |
0 commit comments