基本上我试图让一个 3d 立方体面向鼠标所在的方向。它几乎就在那里,但现在它没有渲染立方体,在我添加这段代码之前它做得很好:
cube.look(xTarget, yTarget);
这是给这个错误:
Uncaught TypeError: Cannot read property 'look' of undefined`
它使 cube
对象不可访问,这是为什么? (......至少,这就是我认为的问题所在)。我在这里做错了什么?
这是相关的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);
}
最佳答案
在这里工作的plunker。 http://plnkr.co/edit/3gZVI8UXRdTW7fLddj9N?p=preview
有几个问题
我变了
init();
animate();
loop();
createCube();
到
init();
createCube();
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
以适本地调用继承的 Mesh 的旋转(this.rotation.x
而不是 this.box.rotation.x
)
关于javascript - 三;js : Error accessing object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32000092/