2015-08-13 54 views
1

基本上我試圖讓一個3d立方體面對鼠標所在的方向。它幾乎在那裏,但現在它不是渲染立方體,它在我添加之前做得很好驗證碼:three; js:訪問對象出錯

cube.look(xTarget, yTarget); 

這是給這個錯誤:

Uncaught TypeError: Cannot read property 'look' of undefined` 

它使得cube對象不可訪問,這是爲什麼? (至少......我認爲這是問題所在)。我在這裏做錯了什麼?

Here's a plunker

下面是相關的JS:

Cube.prototype.updateBody = function(speed){ 
    this.box.rotation.y += (this.tBoxRotY - this.box.rotation.y)/speed; 
    this.box.rotation.x += (this.tBoxRotX - this.box.rotation.x)/speed; 
    this.box.position.x += (this.tBoxPosX-this.box.position.x)/speed; 
    this.box.position.y += (this.tBoxPosY-this.box.position.y)/speed; 
    this.box.position.z += (this.tBoxPosZ-this.box.position.z)/speed; 
} 

Cube.prototype.look = function(xTarget, yTarget){ 
    this.tBoxRotY = rule3(xTarget, -200, 200, -Math.PI/4, Math.PI/4); 
    this.tBoxRotX = rule3(yTarget, -200,200, -Math.PI/4, Math.PI/4); 
    this.tBoxPosX = rule3(xTarget, -200, 200, 70,-70); 
    this.tBoxPosY = rule3(yTarget, -140, 260, 20, 100); 
    this.tBoxPosZ = 0; 
} 

function loop() { 
     render(); 
    var xTarget = (mousePos.x-windowHalfX); 
    var yTarget= (mousePos.y-windowHalfY); 
    console.log('Mouse X position: ' + xTarget +', Y Target = '+yTarget); 
    cube.look(xTarget, yTarget); 
    requestAnimationFrame(loop); 
} 
+0

是正確的plunker鏈接?循環函數沒有cube.look。 –

+0

是的,它在第92行:'Cube.prototype.look = function(xTarget,yTarget){....};'等等,循環函數中的行在149行。 –

回答

2

在這裏工作plunker。 http://plnkr.co/edit/3gZVI8UXRdTW7fLddj9N?p=preview

存在一些問題

我爲了解決您的空引用的問題改變

init(); 
animate(); 
loop(); 
createCube(); 

init(); 
createCube(); 
animate(); 
loop(); 

。 (Animate和循環要求在創建多維數據集之前,才能使用它)。

另外你的繼承(我假設你要繼承?)是不正確的。

我把它更新到

Cube = function(){ 
    var geometry = new THREE.BoxGeometry(50, 50, 50); 

     for (var i = 0; i < geometry.faces.length; i += 2) { 

      var hex = Math.random() * 0xffffff; 
      geometry.faces[ i ].color.setHex(hex); 
      geometry.faces[ i + 1 ].color.setHex(hex); 
     } 

    var material = new THREE.MeshBasicMaterial({ vertexColors: THREE.FaceColors, overdraw: 0.5 }); 

    //I removed this line 
    //Can't do inheritance like this as far as I know? 
    //return box = new THREE.Mesh(geometry, material); 

    //And added this line instead. 
    //Apply your arguments to the Mesh's constructor 
    THREE.Mesh.apply(this, [geometry, material]); 
} 

//I added these lines as well... 
//Set up the prototypes and constructors for inheritance 
Cube.prototype = THREE.Mesh.prototype; 
Cube.prototype.constructor = Cube; 

也更新Cube.prototype.updateBody適當地調用繼承網的旋轉(this.rotation.x而不是this.box.rotation.x