fledgling/src/clock.ts
2025-02-01 13:13:44 -08:00

45 lines
925 B
TypeScript

const MAX_UPDATES_BANKED: number = 20.0;
// always run physics at 240 hz
const UPDATES_PER_MS: number = 1/(1000.0/240.0);
class Clock {
#lastTimestamp: number | undefined;
#updatesBanked: number
constructor() {
this.#lastTimestamp = undefined;
this.#updatesBanked = 0.0
}
recordTimestamp(timestamp: number) {
if (this.#lastTimestamp) {
let delta = timestamp - this.#lastTimestamp;
this.#bankDelta(delta);
}
this.#lastTimestamp = timestamp;
}
popUpdate() {
// return true if we should do an update right now
// and remove one draw from the bank
if (this.#updatesBanked > 1) {
this.#updatesBanked -= 1;
return true
}
return false;
}
#bankDelta(delta: number) {
this.#updatesBanked = Math.min(delta * UPDATES_PER_MS, MAX_UPDATES_BANKED);
}
}
let active: Clock = new Clock();
export function getClock(): Clock {
return active;
}