ZoEM
ZoEM

Reputation: 852

Rotating looped meshes results unexpectedly

I have a three.js project where I'm adding in 100 meshes, that are divided into 10 scenes:

//add 100 meshes to 10 scenes based on an array containing 100 elements
    for (var i = 0; i < data.length; i++) {    
        mesh = new THREE.Mesh(geometry, material);    
        //random positions so they don't spawn on same spot
        mesh.position.x = THREE.Math.randInt(-500, 500);
        mesh.position.z = THREE.Math.randInt(-500, 500); 

They're added in by a loop, and all these meshes are assigned to 10 scenes:

// Assign 10 meshes per scene.
var sceneIndex = Math.floor(i/10);
scenes[sceneIndex].add(mesh);

I also wrote a functionality where I can rotate a mesh around the center of the scene.

But I don't know how to apply the rotation functionality to all meshes while still keeping them divided into their corresponding scenes. This probably sounds way too vague so I have a fiddle that holds all of the relevant code.

If you comment these two lines back in you'll see that the meshes all move to scenes[0], and they all rotate fine the way I wanted, but I still need them divided in their individual scenes.

spinningRig.add(mesh);
scenes[0].add(spinningRig);

How is the code supposed to look like? Waht is the logic to it?

Upvotes: 0

Views: 41

Answers (1)

msun
msun

Reputation: 841

The logic is fairly simple. The simplest format would be to have a separate spinningRig for each scene -- essentially a grouping of the meshes for each scene.

When you create each scene, you'll also create a spinningRig and add + assign it to that scene:

// Setup 10 scenes
for(var i=0;i<10;i++) {
  scenes.push(new THREE.Scene());

  // Add the spinningRig to the scene
  var spinningRig = new THREE.Object3D();
  scenes[i].add(spinningRig);

  // Track the spinningRig on the scene, for convenience.
  scenes[i].userData.spinningRig = spinningRig;
} 

Then instead of adding the meshes directly to the scene, add them to the spinningRig for the scene:

var sceneIndex = Math.floor(i/10);
scenes[sceneIndex].userData.spinningRig.add(mesh);

And finally, rotate the spinningRig assigned to the currentScene:

currentScene.userData.spinningRig.rotation.y -= 0.025;

See jsFiddle: https://jsfiddle.net/712777ee/4/

Upvotes: 2

Related Questions