From ec9a4c24fc7b1bcf31473abb25062542ea04921e Mon Sep 17 00:00:00 2001 From: Bill Rossi Date: Sun, 1 Jun 2025 15:37:12 -0400 Subject: [PATCH] Game loop --- src/game.js | 18 ++++++++++++++++++ src/index.js | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/game.js b/src/game.js index 37715b8..269ddfd 100644 --- a/src/game.js +++ b/src/game.js @@ -2,6 +2,24 @@ export default class Game { constructor(canvas) { this.canvas = canvas this.ctx = canvas.getContext("2d") + this.timestamp = 0 + } + + start() { + requestAnimationFrame(this.loop.bind(this)) + } + + loop(timestamp) { + const dt = timestamp - this.timestamp + this.timestamp = timestamp + this.tick(dt) + this.draw() + + requestAnimationFrame(this.loop.bind(this)) + } + + tick(dt) { + console.log(dt) } draw() { diff --git a/src/index.js b/src/index.js index a800229..6b0098f 100644 --- a/src/index.js +++ b/src/index.js @@ -4,5 +4,6 @@ document.addEventListener("DOMContentLoaded", e => { console.log("Hello, world!") const canvas = document.getElementById("game-canvas") const game = new Game(canvas) - game.draw() + + game.start() })