From a24d2ca07561ff7a7f6695c31128780798d84d5a Mon Sep 17 00:00:00 2001 From: Lieuwe Rooijakkers Date: Sat, 17 Feb 2024 21:09:13 +0100 Subject: use requestAnimationFrame for physics loop --- game.js | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/game.js b/game.js index c1083b4..ee9da93 100644 --- a/game.js +++ b/game.js @@ -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() { -- cgit v1.2.3-54-g00ecf