0
votes

I am using Three.js to create an animation of 100 cubes. For each cube I set its geometry and material and then add it to the scene with: scene.add(cube); I have been storing the positions of the cubes in three arrays: cube_x[99] cube_y[99] cube_z[99]

I do not know how to tell the renderer their positions as they are modified. The following works for one cube when I have only one cube in the scene:

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

I tried making cube into an array to hold the xyz positions of 100 cubes. But I can not seem to call scene.add(cube[i]);

How can I update the position of 100 cubes after scene.add(cube); How do I let three.js know which cube I am trying to move?

Thanks - javascript beginner

1

1 Answers

1
votes

You would basically store a reference to each cube in an array:

// 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);

Now you can iterate over each cube and move it:

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

You would do this within your animation loop.

// 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)
body {margin:0:overflow:hidden}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script>