三; js:访问对象时出错

时间:2015-08-13 23:31:13

标签: javascript three.js

基本上我正试图让一个3d立方体面向鼠标的方向。它几乎就在那里,但是现在它没有渲染立方体,它在我添加这段代码之前做得很好:

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

1 个答案:

答案 0 :(得分:2)

这里的工作人员。 http://plnkr.co/edit/3gZVI8UXRdTW7fLddj9N?p=preview

有几个问题

我改变了

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

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

以修复您的空引用问题。 (Animate和loop要求在它们可以使用之前创建多维数据集)。

你的继承(我假设你要继承?)也不正确。

我将其更新为

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