-
-
Save aglitchman/e688e2607ccb7e7f5db62b492bf84fb6 to your computer and use it in GitHub Desktop.
Defold: semi-fixed timestep for HTML5
This file contains 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
<!-- TODO: Support more than 60hz, i.e. 75hz, 144hz monitors --> | |
<script type="text/javascript"> | |
(function () { | |
var oldRAF = window.requestAnimationFrame; | |
var dummyFunc = function () {}; | |
var prevFrameTime = 0; | |
var accumulator = 0; | |
var FPS = ("{{display.update_frequency}}" | 0); | |
var VSYNC = "{{display.vsync}}" == "true"; | |
if (!FPS || !VSYNC) { | |
console.log("Semi-fixed timestep requires display.vsync = 1, display.update_frequency > 0"); | |
return; | |
} else { | |
console.log("Semi-fixed timestep is ON."); | |
} | |
var FIXED_DT = 1000 / FPS; | |
var disableRender = false; | |
var enableRender = function () { | |
GLFW.params[0x00020003] = false; | |
}; | |
Module.__fixedUpdateSupportFunc = function () { | |
if (disableRender) { | |
GLFW.params[0x00020003] = true; | |
} | |
}; | |
window.requestAnimationFrame = function (callback) { | |
oldRAF(function () { | |
if (!prevFrameTime) prevFrameTime = new Date().getTime() - FIXED_DT; | |
var frameTime = new Date().getTime(); | |
var dt = frameTime - prevFrameTime; | |
prevFrameTime = frameTime; | |
if (dt > FIXED_DT * 4) dt = FIXED_DT * 4; | |
accumulator += dt; | |
var prevFunc = window.requestAnimationFrame; | |
window.requestAnimationFrame = dummyFunc; | |
while (accumulator >= FIXED_DT + FIXED_DT) { | |
accumulator -= FIXED_DT; | |
disableRender = true; | |
callback(); | |
enableRender(); | |
} | |
accumulator -= FIXED_DT; | |
// TODO: Support more than 60hz, i.e. 75hz, 144hz monitors | |
if (accumulator < 0) accumulator = 0; | |
disableRender = false; | |
window.requestAnimationFrame = prevFunc; | |
callback(); | |
}); | |
}; | |
})(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment