I have a simple class that I am using to manage scenes in three.js. I am having issues with the requestAnimationFrame loop finding the function reference. I know I am missing something fundamental here, trapped in some this nightmare. Do I need to use bind or call to pass the this reference to requestAnimationFrame?
var THREE = THREE || {};
var SceneBuddy = SceneBuddy || {};
SceneBuddy = function(scene, camera) {
this.scene = scene;
this.camera = camera;
this.sceneClock = new THREE.Clock();
this.renderer = {};
this.resolution = {};
this.controls = {};
};
//Start Animate
SceneBuddy.prototype.startAnimate = function() {
requestAnimationFrame(this.startAnimate); //this does not work, type error
this.render.call(this);
};
//Render Function
SceneBuddy.prototype.render = function() {
var delta = this.sceneClock.getDelta();
this.controls.update(delta);
this.renderer.render(this.scene,this.camera);
};
//Setup Renderer
SceneBuddy.prototype.initRenderer = function(resolution) {
if (!Detector.webgl) {
Detector.addGetWebGLMessage();
return;
}
else {
var renderer = new THREE.WebGLRenderer({
antialias: true,
preserveDrawingBuffer: true
});
renderer.setSize(resolution.x, resolution.y);
renderer.shadowMapEnabled = true;
this.resolution = resolution;
this.renderer = renderer;
}
};
I am using currently using SceneBuddy like this :
var camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000);
var scene = new THREE.Scene();
var sceneBuddy = new SceneBuddy(scene, camera);
sceneBuddy.initRenderer({x: 940, y: 400});
sceneBuddy.attachRenderer(container); //attaches renderer to dom element
sceneBuddy.initControls();
sceneBuddy.startAnimate(); // broken.
Use bind
when passing a function to specify what this
will be when the function is called:
SceneBuddy.prototype.startAnimate = function() {
requestAnimationFrame(this.startAnimate.bind(this));
this.render();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With