Beginner Question: Animating an Array of Meshes?

Hello,

I am new to three.js, and have some beginner questions.

I am interesting in animating individual materials within a group, and also animating the group as a whole.

  1. Is there a better way to create a grid of geometries than nested for-loops? I feel like this is probably bad practice for performance, but I am not sure.
//Nested for-loop to create a 10x10x10 grid of cubes
//Here I am storing the meshes in an array to animate each object independently
//Geometry and material are all ready defined.

let cubeArray = [];
for (var k = 0; k < 10; k++) {
  for (var j = 0; j < 10; j++) {
    for (var i = 0; i < 10; i++) {
      var object = new THREE.Mesh(geometry, material);
      object.position.x = i;
      object.position.y = j;
      object.position.z = k;
      cubeArray .push("object");
      scene.add(object);
    }
  }
}
  1. My animation frame only works on the last instance of ‘object’ (makes sense), and if I loop over the array nothing happens. Why doesn’t the array update?
//**In update function**

//Only last 'object' rotates
  object.rotation.x += 0.001;

//Nothing happens
    for (var u = 0; u < cubeArray.length; u++) {
      cubeArray[u].position.x +=0.001;
    }

Thanks!

Hi!
You have to push object, not "object" (means, object itself, not a string with this word).

1 Like

Thanks! I can’t believe I missed that.

How can I move the grid as a whole? Is there anyway to add some surrounding container and rotate that?

https://pedantic-chandrasekhar-30ecf0.netlify.com/

Yes, you can group the boxes with THREE.Group() and move the grid as a whole :slight_smile:
Yes, there is a way to create a surrounding container and rotate it :slight_smile:

Updated fiddle: https://jsfiddle.net/prisoner849/m64d5rwn/

Awesome thanks!

You’re welcome :slight_smile: