Skip to content

Instantly share code, notes, and snippets.

@ezekielchentnik
Last active Jul 22, 2019
Embed
What would you like to do?
Three.js Game Loop
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();
}
}
/*
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