Tony
Tony

Reputation: 219

THREE.js Object Won't Rotate

I have a Blender object that is able to be displayed on my web page using THREE.js, however the object isn't rotating when my loop function is called.

I'm trying to maintain an OOP approach while working with js.

Here's my code snippet.

var scene, camera, renderer, box;

function createScene() {
    scene = new THREE.Scene();

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(0x3399ff);

    camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
    camera.position.z = 10;

    container = document.getElementById('world');
    container.appendChild(renderer.domElement);
}

function createLight() {
    light = new THREE.PointLight(0xffffff, 1.2);
    light.position.set(0,0,6);

    scene.add(light);
}

function createBox() {
    box = new Box();
}

Box = function() {
    this.mesh = new THREE.Object3D();

  var loader = new THREE.JSONLoader();
  loader.load('json/model.json', function(geometry, materials) {
      this.mesh = new THREE.Mesh(geometry, new THREE.MultiMaterial(materials));
      this.mesh.scale.x = this.mesh.scale.y = this.mesh.scale.z = 0.75;
      this.mesh.translation = geometry.center();
      scene.add(mesh);
  });
}

Box.prototype.rotateBox = function() {
    if (!this.mesh) {
        return;
    }

    this.mesh.rotation.x += .001;
    this.mesh.rotation.y += .01;
}

function loop() {
    requestAnimationFrame(loop);
    box.rotateBox();
    renderer.render(scene, camera);
}

function init() {
    createScene();
    createLight();
    createBox();
    loop();
}

window.addEventListener('load', init, false);

Upvotes: 0

Views: 1653

Answers (1)

Radio
Radio

Reputation: 2863

I think it's a scope issue. Your code as provided would throw errors. You might try something like this:

Box = function() {
  this.mesh = false;
  var loader = new THREE.JSONLoader();
  var scope = this;
  loader.load('json/model.json', function(geometry, materials) {
      scope.mesh = new THREE.Mesh(geometry, new THREE.MultiMaterial(materials));
      scope.mesh.scale.x = scope.mesh.scale.y = scope.mesh.scale.z = 0.75;
      scope.mesh.translation = geometry.center();
      scene.add(scope.mesh);
  });
}

Box.prototype.rotateBox = function() {
    if (!this.mesh) {
        return;
    }

    this.mesh.rotation.x += .001;
    this.mesh.rotation.y += .01;
}

Your scope of the "light" object is also left unhandled and needs to be fixed.

Upvotes: 1

Related Questions