无法在Three.js中为线框旋转设置动画

时间:2016-02-18 16:20:13

标签: javascript three.js

我试图让线框在场景中旋转。

当我移除BoxHelper时,动画会起作用,但我想为没有对角线而不是实体对象的立方体线框设置动画。

Codepen演示:

Demo

代码:

var  w = window.innerWidth, h = window.innerHeight,
scene = new THREE.Scene(), 
camera = new THREE.PerspectiveCamera(75, w/h, 0.1, 1000),
renderer = new THREE.WebGLRenderer(),
geometry = new THREE.BoxGeometry( 1, 1, 1 ),
material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ),
mesh = new THREE.Mesh( geometry, material ),
cube = new THREE.BoxHelper(mesh);

cube.material.color.setRGB(25,25,25);
scene.add(cube);

camera.position.z = 2;
renderer.setSize(w,h);
document.body.appendChild(renderer.domElement);


function render(){
  requestAnimationFrame( render );
  cube.rotation.x += 1;
  renderer.render(scene, camera );
}

render();

1 个答案:

答案 0 :(得分:2)

THREE.BoxHelper个实例的位置与THREE.Mesh的位置相关联。要使代码生效,您必须将网格物体添加到场景中并旋转网格物体。您的帮助器将随之而来。

如果您不想显示网格,只需设置mesh.visible = false;

即可

此代码有效:

var w = window.innerWidth, h = window.innerHeight,
    scene = new THREE.Scene(), 
    camera = new THREE.PerspectiveCamera(75, w/h, 0.1, 1000),
    renderer = new THREE.WebGLRenderer(),
    geometry = new THREE.BoxGeometry( 1, 1, 1 ),
    mesh = new THREE.Mesh( geometry );

camera.position.z = 2;  
renderer.setSize(w,h);
document.body.appendChild(renderer.domElement);

mesh.visible = false; //<-- hide mesh
scene.add(mesh);      //<-- add mesh to scene

cube = new THREE.BoxHelper(mesh);   
cube.material.color.setRGB(25,25,25);
scene.add(cube);

function render(){
    mesh.rotation.y += 0.01; //<-- rotate the mesh

    requestAnimationFrame( render );
    renderer.render( scene, camera );
}

render();