如何在three.js中的animate()函数中改变网格的位置?

Fra*_*act 2 javascript animation three.js

我在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);
Run Code Online (Sandbox Code Playgroud)

我想在函数 animate() 中更改此网格的位置;

我已经尝试了几件事,但下面的例子都没有工作:

1.:

sphere.position.set = new THREE.Vector3(20, 20, 20);
Run Code Online (Sandbox Code Playgroud)

2.:

 sphere.position.set(20, 20, 20);
Run Code Online (Sandbox Code Playgroud)

3.:

sphere.position.x += 1;
Run Code Online (Sandbox Code Playgroud)

4.:

sphere.translateX(50);
Run Code Online (Sandbox Code Playgroud)

结果每次都是黑屏。

奇怪的是,我可以在同一代码区域中更改相机和灯光的位置:

                pointLight.position.set(10, 20, 03);
                camera.position.set(12, 44, 13);
                camera.lookAt(new THREE.Vector3(33, 45, 54));
Run Code Online (Sandbox Code Playgroud)

然而,网格的 position.set 失败了。是否可以在函数 animate() 中更改网格的位置?

我试过了:

"sphere.position.x = 20;"
Run Code Online (Sandbox Code Playgroud)

结果是一个黑色的窗口。

您可以在下面看到详细的控制台日志:

日志对“sphere.position.x = 20;”上方行的注释:

"Uncaught TypeError: Cannot set property 'x' of undefined"
Run Code Online (Sandbox Code Playgroud)

此问题的日志的其他详细信息:

"animate @ index_final.html:260
(anonymous function) @ index_final.html:98
parse @ ColladaLoader.js:225
request.onreadystatechange @ ColladaLoader.js:113"
Run Code Online (Sandbox Code Playgroud)

Fal*_*ele 6

您的sphere变量引用网格不在范围animate()功能。通过删除以下内容使其成为全局变量var

sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

然后在animate()通话中sphere.position.set(20, 20, 20);应该这样做,

或者,如果您想为运动设置动画: sphere.position.x += 1;


免责声明:请记住,应避免使用全局变量,因为它们是邪恶的>:)