2017-04-05 141 views
0

我有一個Blender對象可以使用THREE.js顯示在我的網頁上,但是當我的循環函數被調用時,對象不會旋轉。THREE.js對象不會旋轉

我試圖在使用js時保持OOP方法。

這是我的代碼片段。

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); 

回答

1

我認爲這是一個範圍問題。您提供的代碼會拋出錯誤。你可以嘗試這樣的事:

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; 
} 

你的「輕」對象的範圍也左未處理,需要修復。

+0

所以這是一個範圍問題,我所要做的就是將'this'存儲到變量中。然後,我會在任何'this'的地方使用該變量。你能解釋爲什麼把'this'存入一個變量可以解決這個問題嗎? – Tony

+0

在您的示例代碼中,您在作爲loader.load參數提供的onLoad函數內使用了「this」。因此,「this」是指在這種情況下的加載器。要了解JavaScript中的範圍,請參閱:http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Radio