Search code examples
ember.jsthree.jsember-controllers

three.js animations in ember js


How should i create a render loop of three.js for animations in ember js. The code that i have till now is

import Ember from 'ember';

export default Ember.Controller.extend({
  scene: new THREE.Scene(),
  camera: new THREE.PerspectiveCamera(75,
    window.innerWidth/window.innerHeight,1,500),
  renderer: new THREE.WebGLRenderer(),
  init: function() {
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(this.renderer.domElement);
    this.renderPreloader();
  },
  renderPreloader:function() {
    var geometry = new THREE.BoxGeometry( 1, 1, 1 );
    var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    var cube = new THREE.Mesh(geometry,material);
    this.scene.add(cube);
    this.camera.position.set(2,2,2);
    this.camera.lookAt(cube.position);
    this.renderer.render(this.scene,this.camera);
    this.renderLoop();
  },
  renderLoop: function() {
    requestAnimationFrame(this.renderLoop);
    this.camera.position.x = this.camera.position.x+0.01;
    this.renderer.render(this.scene,this.camera);
  }
});

The error that i am getting is this is not defined at requestAnimationFrame. What is the proper way to get through this ?


Solution

  • To pass scope correctly, do :

    requestAnimationFrame(this.renderLoop.bind(this));

    or

    requestAnimationFrame(() => {this.renderLoop()});