如何在scene.add(object)之后移动多个对象;

时间:2017-12-04 03:59:44

标签: three.js

我正在使用Three.js来创建100个立方体的动画。 对于每个立方体,我设置其几何和材质,然后将其添加到场景中: scene.add(立方体); 我一直在三维数组中存储立方体的位置:cube_x [99] cube_y [99] cube_z [99]

我不知道如何告诉渲染器修改它们的位置。当场景中只有一个立方体时,以下适用于一个立方体:

cube.position.x = 300; cube.position.y = 000;

我尝试将立方体制作成数组来保存100个立方体的xyz位置。但我似乎无法调用scene.add(cube [i]);

如何在scene.add(cube)之后更新100个立方体的位置; 我怎么让three.js知道我想要移动哪个立方体?

谢谢 - javascript初学者

1 个答案:

答案 0 :(得分:1)

您基本上会在数组中存储对每个多维数据集的引用:

// reference array
var cubes = [];

// create cube mesh
var cube = new THREE.Mesh(new THREE.BoxGeometry(), someMaterial);

// push a reference to array
cubes.push(cube);

// add same cube to scene
scene.add(cube);

现在,您可以遍历每个多维数据集并移动它:

cubes.forEach(function(cube) {
  cube.position.z -= 0.1;  // move for example in Z direction
});

您可以在动画循环中执行此操作。



// Setup a simple demo scene
var scene = new THREE.Scene();
var cam = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, maxDist);
var renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// STore our cubes somewhere, dist for random generation and clipping
var cubes = [], maxDist = 500, r = Math.random, materials = [];
for(var i = 0; i < 7; i++) materials.push(new THREE.MeshBasicMaterial({color: (r()*0xffffff)&0xffffff|0x999999}));

// Add and store some cubes
for(i = 0; i < 3000; i++) {
  var cube = new THREE.Mesh(new THREE.BoxBufferGeometry(), materials[i % materials.length]);
  cubes.push(cube); // store to our array
  cube.position.set(r()*maxDist*2-maxDist, r()*maxDist*2-maxDist, r()*maxDist*2-maxDist); // random positions
}
scene.add(...cubes);	//es6, add to scene
cam.position.z = maxDist;

// Animate cubes
function loop(time) {
  for(i = 0, cube; i < cubes.length; i++) {  // for each cube do:
  	cube = cubes[i];
  	cube.position.z -= 1; // move on Z in this demo
    if (cube.position.z < -maxDist) cube.position.z = maxDist;  // reset position for demo
  }
  cam.rotation.z = Math.sin(time*0.0003);      // add some camera action
  cam.rotation.y = Math.sin(time*0.0005)*0.3;  // add some camera action
  renderer.render(scene, cam);                 // render everything
  requestAnimationFrame(loop)
};
requestAnimationFrame(loop)
&#13;
body {margin:0:overflow:hidden}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>
&#13;
&#13;
&#13;