Reputation: 704
Currently working with Three.js.
What I have:
As shown in the figure and code below i have a for loop that create a specific object on random position in the scene.
//Create Objects
var geometry = new THREE.CylinderBufferGeometry( 0, 10, 30, 4, 1 );
var material = new THREE.MeshPhongMaterial( { color: 0xffffff, flatShading: true } );
for(var i=0; i<100; i++) {
var mesh = new THREE.Mesh( geometry, material );
mesh.position.x = getRandomInt(-500,500);
mesh.position.y = getRandomInt(10, 100);
mesh.position.z = getRandomInt(-500,500);
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene_Main.add( mesh );
}
My Question:
How to create random objects of different material and geometry in a for loop?
Can i use the idea of creating an array that holds the specific geometry/material and if so how to store this in an array and how to use it?
array idea:
var geometryList = [cube, pyramid, sphere, donut, ...];
var materialList = [ .. what posibilities I have here? .. ];
for(var i=0; i<100; i++) {
var mesh = new THREE.Mesh( geometryList[random[n]], materialList[random[n]] );
....
}
Upvotes: 0
Views: 708
Reputation: 704
var materialList = [];
for(var i=0; i<150; i++) {
//Prepare different material for each object
var color = new THREE.Color( 0xffffff );
color.setHex( Math.random() * 0xffffff );
materialList.push(new THREE.MeshBasicMaterial({ color: color }));
//Prepare diferent sizes for the objects
var geometrySize_2 = getRandomInt(5,30);
//Create 50 Pyramids
if(i <= 50){
var geometry1 = new THREE.CylinderBufferGeometry( 0, 10, 30, 4, 1 );
var mesh = new THREE.Mesh( geometry1, materialList[i] );
mesh.position.x = getRandomInt(-500,500);
mesh.position.y = getRandomInt(10, 150);
mesh.position.z = getRandomInt(-500,500);
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene_Main.add( mesh );
}
//Create 50 Cubes
else if(i <= 100 && i>= 50){
var geometry2 = new THREE.BoxGeometry(geometrySize_2,geometrySize_2,geometrySize_2);
var mesh = new THREE.Mesh( geometry2, materialList[i] );
mesh.position.x = getRandomInt(-500,500);
mesh.position.y = getRandomInt(10, 150);
mesh.position.z = getRandomInt(-500,500);
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene_Main.add( mesh );
}
//Create 100 Spheres
else if(i <= 150 && i>= 50){
var geometry3 = new THREE.SphereGeometry( 5, 32, 32 );
var mesh = new THREE.Mesh( geometry3, materialList[i] );
mesh.position.x = getRandomInt(-500,500);
mesh.position.y = getRandomInt(10, 150);
mesh.position.z = getRandomInt(-500,500);
mesh.updateMatrix();
mesh.matrixAutoUpdate = false;
scene_Main.add( mesh );
}
}
Upvotes: 0
Reputation: 12632
You can do anything you want really. You just have to populate your materialList[]
One way
for(var i=0; i<100; i++) {
color = new THREE.Color( 0xffffff );
color.setHex( Math.random() * 0xffffff );
materialList.push(new THREE.MeshBasicMaterial({ color: color }));
}
of cource your random[n]
function must return something between [0-99]
Upvotes: 1