@spearwolf/twopoint5d
Version:
Create 2.5D realtime graphics and pixelart with WebGL and three.js
82 lines • 2.53 kB
JavaScript
const getCurrentTime = (time) => (typeof time === 'number' && !Number.isNaN(time) ? time : performance.now() / 1000);
export class Chronometer {
#timeStart;
#currentTime;
#deltaTime;
#lostTime;
#recentlyLostTime;
#pausedAt;
#isRunning;
get time() {
return this.#currentTime - this.#timeStart - this.#lostTime - this.#recentlyLostTime;
}
get deltaTime() {
return this.#deltaTime;
}
get timeStart() {
return this.#timeStart;
}
get lostTime() {
return this.#lostTime + this.#recentlyLostTime;
}
get isRunning() {
return this.#isRunning;
}
constructor(time, maxDeltaTime = 0) {
const curTime = getCurrentTime(time);
this.#timeStart = curTime;
this.#currentTime = curTime;
this.#deltaTime = 0;
this.#lostTime = 0;
this.#recentlyLostTime = 0;
this.#pausedAt = curTime;
this.#isRunning = true;
this.maxDeltaTime = maxDeltaTime;
}
update(time) {
const previousTime = this.#currentTime;
this.#currentTime = getCurrentTime(time);
const deltaTime = this.#currentTime - previousTime;
if (this.#isRunning) {
if (this.maxDeltaTime > 0 && deltaTime > this.maxDeltaTime) {
this.#lostTime += deltaTime - this.maxDeltaTime;
this.#deltaTime = this.maxDeltaTime;
}
else {
this.#deltaTime = deltaTime;
}
}
else {
this.#recentlyLostTime += deltaTime;
}
}
stop(time) {
if (this.#isRunning) {
this.#isRunning = false;
this.#recentlyLostTime = 0;
this.#pausedAt = getCurrentTime(time);
}
}
start(time) {
if (!this.#isRunning) {
this.#isRunning = true;
const now = getCurrentTime(time);
const gap = Math.max(0, now - this.#pausedAt - this.#recentlyLostTime);
this.#lostTime += this.#recentlyLostTime + gap;
this.#recentlyLostTime = 0;
this.#currentTime = now;
this.#deltaTime = 0;
}
}
reset(time) {
const curTime = getCurrentTime(time);
this.#timeStart = curTime;
this.#currentTime = curTime;
this.#deltaTime = 0;
this.#lostTime = 0;
this.#recentlyLostTime = 0;
this.#pausedAt = curTime;
this.#isRunning = true;
}
}
//# sourceMappingURL=Chronometer.js.map