fix game loop timer
This commit is contained in:
+19
-4
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user