aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLieuwe Rooijakkers <lieuwerooijakkers@gmail.com>2024-02-17 21:09:13 +0100
committerLieuwe Rooijakkers <lieuwerooijakkers@gmail.com>2024-02-17 21:09:18 +0100
commita24d2ca07561ff7a7f6695c31128780798d84d5a (patch)
tree92f70667c6d1faa15c2697fbb0bdb8eb325966c6
parentb585663f07f62094fc2a8a02dcee41e82fa44077 (diff)
use requestAnimationFrame for physics loop
-rw-r--r--game.js26
1 files 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() {