diff options
-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() { |