fix game loop timer

This commit is contained in:
2025-01-12 10:57:22 +09:00
parent e0dd7dcaf3
commit d9849f770b
6 changed files with 123 additions and 13 deletions
+19 -4
View File
@@ -8,12 +8,14 @@ export default class Game {
currentTick = 0
width = 2000
height = 2000
running = false
nextTick = 0
#entities = []
#eventEmitter = new EventEmitter()
#projectiles = []
#terrains = []
#tickBudget = Math.floor(1000 / this.tickRate)
#tickBudget = 1000 / this.tickRate
get entities() { return this.#entities }
get eventEmitter() { return this.#eventEmitter }
@@ -80,10 +82,23 @@ export default class Game {
}
}
gameLoop() {
const tickBudget = this.#tickBudget
if (this.nextTick != null) {
const nextTick = this.nextTick
this.nextTick = null
let start = performance.now()
while (start < nextTick) { start = performance.now() }
this.update()
this.nextTick = start + tickBudget
}
}
start() {
const start = performance.now()
this.update()
setTimeout(() => this.start(), Math.max(0, this.#tickBudget - (performance.now() - start)))
setInterval(() => this.gameLoop(), 1)
}
update() {