diff --git a/static/js/config.js b/static/js/config.js index ffd7073..f82f1a3 100644 --- a/static/js/config.js +++ b/static/js/config.js @@ -6,6 +6,9 @@ const JUMP_POWER = -12; const GROUND_Y = 350; const GAME_SPEED = 5; const CHUNK_SIZE = 60; +const TARGET_FPS = 60; +const MS_PER_TICK = 1000 / TARGET_FPS; + // RNG Klasse class PseudoRNG { diff --git a/static/js/main.js b/static/js/main.js index f6f2f53..cbb2408 100644 --- a/static/js/main.js +++ b/static/js/main.js @@ -44,14 +44,39 @@ function gameOver(reason) { drawGame(); } -function gameLoop() { - if (!isLoaded) return; - if (isGameRunning && !isGameOver) { - updateGameLogic(); currentTick++; score++; - const scoreEl = document.getElementById('score'); if (scoreEl) scoreEl.innerText = Math.floor(score / 10); - if (currentTick - lastSentTick >= CHUNK_SIZE) sendChunk(); +function gameLoop(timestamp) { + requestAnimationFrame(gameLoop); + + if (!isLoaded || !isGameRunning || isGameOver) { + lastTime = timestamp; + return; } - drawGame(); requestAnimationFrame(gameLoop); + + if (!lastTime) lastTime = timestamp; + const deltaTime = timestamp - lastTime; + lastTime = timestamp; + + if (deltaTime > 1000) { + accumulator = 0; + return; + } + + accumulator += deltaTime; + + while (accumulator >= MS_PER_TICK) { + updateGameLogic(); + currentTick++; + score++; + + if (currentTick - lastSentTick >= CHUNK_SIZE) sendChunk(); + + accumulator -= MS_PER_TICK; + } + + const scoreEl = document.getElementById('score'); + if (scoreEl) scoreEl.innerText = Math.floor(score / 10); + + drawGame(); } async function initGame() { diff --git a/static/js/state.js b/static/js/state.js index d382ec6..373c95f 100644 --- a/static/js/state.js +++ b/static/js/state.js @@ -12,6 +12,10 @@ let lastSentTick = 0; let inputLog = []; let isCrouching = false; +// Tick Time +let lastTime = 0; +let accumulator = 0; + // Grafiken let sprites = {}; let playerSprite = new Image();