Last active
July 22, 2019 04:27
-
-
Save ezekielchentnik/80a06cd62efada5840afc9e863c5a78e to your computer and use it in GitHub Desktop.
Three.js Game Loop
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
import { EventDispatcher } from "three"; | |
export default class Loop extends EventDispatcher { | |
constructor(fps = 60, speed = 1) { | |
super(); | |
this._timeStep = (1000 / fps) * speed; | |
this._prevTime = null; | |
this._lagTime = 0; | |
this._frame = this._frame.bind(this); | |
this._frameId = null; | |
} | |
_frame() { | |
const curTime = performance.now(); | |
const dt = Math.min(1000, curTime - this._prevTime); | |
this._prevTime = curTime; | |
this._lagTime += dt; | |
while(this._lagTime > this._timeStep) { | |
this._lagTime -= this._timeStep; | |
this.dispatchEvent({ type: 'update', timeStep: this._timeStep }); | |
} | |
this.dispatchEvent({ type: 'render', dt }); | |
this._frameId = requestAnimationFrame(this._frame); | |
} | |
start() { | |
if(this._prevTime === null) { | |
this.dispatchEvent({ type: 'init' }); | |
} | |
this.dispatchEvent({ type: 'start' }); | |
this._prevTime = performance.now(); | |
this._frame(); | |
} | |
stop() { | |
this.dispatchEvent({ type: 'stop' }); | |
cancelAnimationFrame(this._frameId); | |
this._frameId = null; | |
} | |
dispose() { | |
this.stop(); | |
super.dispose(); | |
} | |
} |
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
/* | |
let start = window.animationTime; | |
let rate = 10; // Hz | |
let duration = 10; // s | |
let lastFrameNumber; | |
function animate() { | |
let elapsed = window.animationTime - start; | |
if (elapsed < duration) { | |
window.requestAnimationFrame(animate); | |
} | |
let frameNumber = Math.round(elapsed/(1000/rate)); | |
if (frameNumber == lastFrameNumber) { | |
return; | |
} | |
lastFrameNumber = frameNumber; | |
// call update | |
} | |
window.requestAnimationFrame(animate); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment