How to move multiple meshs in different directions with three.js?

383 Views Asked by At

I have a problem. With the for loop I have created 100 meshes. They all have the position of 0,0,0. But I want that these 100 meshes move separated in all different directions.

This is my code to create the 100 meshes

for(var i = 0; i < 100; i++)
{
var geometry = new THREE.BoxGeometry(2, 2, 2);
var material = new THREE.MeshBasicMaterial( { color: 0x2194ce} );
mesh = new THREE.Mesh( geometry, material);

mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = 0;    
scene.add(mesh);    
}

This is the code how I though to move the 100 meshes, but It move only one mesh

function render(){
        requestAnimationFrame( render );
            mesh.position.x +=0.1;
            renderer.render(scene, camera); 

        }
1

There are 1 best solutions below

0
On

You have only the last mesh in your mesh variable. In order to move all, you can store them in an array, then iterate the array in your render loop and assign the New Position. mesh.position.z = 0; meshes.push( mesh );

And in render:

 for( var i=0; i<meshes.length; i++){
      meshes[i].position.x += 0.1;
 }

I've not tested this.