问题描述
我在three.js中有一个简单的网格(实现为three.js-master \\ examples \\ webgl_loader_collada_keyframe.html):
function init() {
...
...
var sphereGeometry = new THREE.SphereGeometry( 50, 32, 16 );
var sphereMaterial = new THREE.MeshLambertMaterial( {color: 0x8888ff} );
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(10, 10, 10);
scene.add(sphere);
我想在函数animate()中更改此网格的位置;
我尝试了几件事,但下面的例子都没有起作用:
1:
sphere.position.set = new THREE.Vector3(20, 20, 20);
2:
sphere.position.set(20, 20, 20);
3:
sphere.position.x += 1;
4:
sphere.translateX(50);
结果是每次都是黑屏。
奇怪的是,我可以在相同的代码区域中更改相机和灯光位置:
pointLight.position.set(10, 20, 03);
camera.position.set(12, 44, 13);
camera.lookAt(new THREE.Vector3(33, 45, 54));
然而,网格的position.set失败。 是否可以在函数animate()中更改网格的位置?
我试过了:
"sphere.position.x = 20;"
结果是一个黑色的窗口。
您可以在下面看到详细的控制台日志:
日志对“sphere.position.x = 20;”上面一行的注释:
"Uncaught TypeError: Cannot set property 'x' of undefined"
此问题的日志的其他详细信息:
"animate @ index_final.html:260
(anonymous function) @ index_final.html:98
parse @ ColladaLoader.js:225
request.onreadystatechange @ ColladaLoader.js:113"
1楼
引用网格的sphere变量不在animate()函数的范围内。
通过删除var使其成为全局变量:
sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
然后在animate()调用sphere.position.set(20, 20, 20);
应该这样做,
或者如果你想动画运动: sphere.position.x += 1;
免责声明:请记住全局变量应该避免因为它们是邪恶的 > :)