Created
November 11, 2022 08:51
-
-
Save takumifukasawa/dd853d050efe63cdbd57d3d84f52a9d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class TimeAccumulator { | |
targetFPS; | |
#callback; | |
#lastTime; | |
maxChaseCount; | |
constructor(targetFPS, callback, maxChaseCount = 60) { | |
this.targetFPS = targetFPS; | |
this.#callback = callback; | |
this.maxChaseCount = maxChaseCount; | |
} | |
// time [sec] | |
start(time) { | |
this.#lastTime = time; | |
} | |
// time [sec] | |
exec(time) { | |
const interval = 1 / this.targetFPS; | |
if((time - interval) >= this.#lastTime) { | |
const elapsedTime = time - this.#lastTime; | |
const n = Math.floor(elapsedTime / interval); | |
if(n > this.maxChaseCount) { | |
console.warn("[TimeAccumulator.exec] jump frame"); | |
this.#lastTime += interval * n; | |
this.#callback(this.#lastTime, interval); | |
return; | |
} | |
const loopNum = Math.min(this.maxChaseCount, n); | |
for(let i = 0; i < loopNum; i++) { | |
this.#lastTime += interval; | |
this.#callback(this.#lastTime, interval); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment