Last active
October 28, 2020 18:09
-
-
Save wmcmurray/8819e8356b4bba52dbd2f1b11cc543b2 to your computer and use it in GitHub Desktop.
Ensure consistent frame-rate in a javascript game/app (threejs or anything else).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Wraps an animation loop function so it can be executed at a specific frame-rate | |
* loop {Function} = The function you want to execute each frames | |
* fps {Number} = The desired frame rate | |
*/ | |
function createFpsCap(loop, fps = 60) { | |
let targetFps = 0, fpsInterval = 0; | |
let lastTime = 0, lastOverTime = 0, prevOverTime = 0, deltaTime = 0; | |
function updateFps(value) { | |
targetFps = value; | |
fpsInterval = 1000 / targetFps; | |
} | |
updateFps(fps); | |
return { | |
// the targeted frame rate | |
get fps() { | |
return targetFps; | |
}, | |
set fps(value) { | |
updateFps(value); | |
}, | |
// the frame-capped loop function | |
loop: function(time) { | |
deltaTime = time - lastTime; | |
if(deltaTime < fpsInterval) { | |
return; | |
} | |
prevOverTime = lastOverTime; | |
lastOverTime = deltaTime % fpsInterval; | |
lastTime = time - lastOverTime; | |
deltaTime -= prevOverTime; | |
return loop(deltaTime); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also made a repository based on this : https://github.com/wmcmurray/game-loop-js for ease of use !