diff options
author | Lieuwe Rooijakkers <lieuwerooijakkers@gmail.com> | 2024-02-17 21:09:13 +0100 |
---|---|---|
committer | Lieuwe Rooijakkers <lieuwerooijakkers@gmail.com> | 2024-02-17 21:09:18 +0100 |
commit | a24d2ca07561ff7a7f6695c31128780798d84d5a (patch) | |
tree | 92f70667c6d1faa15c2697fbb0bdb8eb325966c6 | |
parent | b585663f07f62094fc2a8a02dcee41e82fa44077 (diff) |
use requestAnimationFrame for physics loop
-rw-r--r-- | game.js | 26 |
1 files changed, 18 insertions, 8 deletions
@@ -172,7 +172,7 @@ function openGame() { socket.emit("open", gameId); } -var graphicsLoopId = null, physicsLoopId = null; +var graphicsLoopId = null, loopPhysics = false; function startGraphicsLoop() { // undrawElements(); @@ -187,9 +187,18 @@ function stopGraphicsLoop() { } function startPhysicsLoop() { - var interval = 1 / 120; - physicsLoopId = setInterval(function() { - var info = advancePhysics(interval); + let prev = performance.now(); + + loopPhysics = true; + function tick() { + if (!loopPhysics) { + return; + } + + const now = performance.now(); + var info = advancePhysics((now - prev) / 1e3); + prev = now; + if (info.bounce || info.otherBounce) { playSound("bounce"); } @@ -205,13 +214,14 @@ function startPhysicsLoop() { stopPhysicsLoop(); playSound("miss"); } - }, interval * 1000); + + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); } function stopPhysicsLoop() { - if (physicsLoopId == null) return; - clearInterval(physicsLoopId); - physicsLoopId = null; + loopPhysics = false; } function initPhysics() { |