Pete Sansford
Pete Sansford

Reputation: 11

Threejs Multiple Mesh animation

I am very new to threejs, and I have created a for loop to draw 400 cylinders. Everything is fine and they are called into the scene and rendered properly. When I go to animate the objects, only one of the 400 appears to rotate. How can I rotate all of the cylinders?

Code:

        for( var j = 0; j < 400; j++){
                abgeometry2 = new THREE.CylinderGeometry (1, 5, 8, 4);
              abmesh2 = new THREE.MeshPhongMaterial({color: 0x3B170B,
                    wireframe: false });
              mesh2 = new THREE.Mesh(abgeometry2, abmesh2);
                mesh2.position.x = Math.random() * 400 - 200;
                mesh2.position.y = Math.random() * 400 - 200;
                mesh2.position.z = Math.random() * 400 - 200;
                scene.add( mesh2 );
            }

And in the animate I put : mesh2.rotation.z += 0.06; I know I may be doing something stupid but I'm not quite familiar with threejs.

Upvotes: 1

Views: 1354

Answers (1)

Reign of Error
Reign of Error

Reputation: 625

You're only applying the rotation to the last cylinder since they're all assigned to mesh2 during the loop.

Try something like this:

var numCylinders = 400;

var cylinders = [];

var geo = new THREE.CylinderGeometry (1, 5, 8, 4);
var mesh = new THREE.MeshPhongMaterial({color: 0x3B170B, wireframe: false });

for (var i = 0; i < numCylinders; i++){
    var curCylinder = new THREE.Mesh(geo, mesh);

    curCylinder.position.x = Math.random() * 400 - 200;
    curCylinder.position.y = Math.random() * 400 - 200;
    curCylinder.position.z = Math.random() * 400 - 200;

    scene.add(curCylinder);

    cylinders.push(curCylinder);
}

var render = function () {
    requestAnimationFrame( render );

    for (var i = 0; i <numCylinders; i++){
        cylinders[i].rotation.z += 0.06;
    }

    renderer.render(scene, camera);
};

render();

Upvotes: 5

Related Questions