Reputation: 885
I'm trying to make a function that will change material
color for randomly choosen 10 objects, but I don't know how to "connect" it into either array or vectors. I've tried putting into color(selector)
some of arrays like meshArrayX
but then, the positions of objects are undefined and won't color any of object at all.
var mesh, scene,
MeshBasicMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0.3,
transparent: true
});
var BoxGeometry = new THREE.BoxGeometry(16, 16, 16);
function random(){
var random = [0, 16, 32];
var randomValue = random[Math.floor(random.length * Math.random())];
console.log(randomValue);
}
function color(selector){
for(var v=0; v<10; v++){
selector.position.x = random();
selector.position.y = random();
selector.position.z = random();
selector.material.color.setHex( 0x0000ff);
}
}
var meshArrayX = [];
for (var x=0; x<3; x++) {
var meshArrayY = [meshArrayX.push(mesh = new THREE.Mesh(BoxGeometry, MeshBasicMaterial))];
for(var y=0; y<3; y++){
var meshArrayZ = [meshArrayY.push(mesh = new THREE.Mesh(BoxGeometry, MeshBasicMaterial))];
for(var z=0; z<3; z++){
meshArrayZ.push(mesh = new THREE.Mesh(BoxGeometry, MeshBasicMaterial));
mesh.position.x = 16*x;
mesh.position.y = 16*y;
mesh.position.z = 16*z;
scene.add(mesh);
console.log(meshArrayX.length, meshArrayY.length-1, meshArrayZ.length-1, mesh.position);
}
}
}
color(mesh);
Upvotes: 0
Views: 1858
Reputation: 796
I'm not sure I understood what you asked, but I try to help you.
I think that you want to create an array of 27 box (3x3x3) but I dont understand your code..., you use a global variable mesh, but add to scene only in the z loop.
My code fot this operation is:
var BoxGeometry = new THREE.BoxGeometry(5, 5, 5);
var meshArray = [];
for (var x=0; x<3; x++) {
for(var y=0; y<3; y++){
for(var z=0; z<3; z++){
var mesh = new THREE.Mesh(BoxGeometry, material.clone());
meshArray.push(mesh);
mesh.position.x = 16*x;
mesh.position.y = 16*y;
mesh.position.z = 16*z;
scene.add(mesh);
console.log(meshArray.length, mesh.position);
}
}
}
notice the "material.clone()" is necessary to create new instance of material for each mesh.
And your color function can be like this:
function color(selector){
for(var v=0; v<10; v++){
var pos= Math.floor((Math.random() * selector.length));
selector[pos].material.color.setHex( 0x0000ff );
}
}
called by:
color(meshArray);
Now, when you call the color function you select 10 random box from the array and apply the color.
I hope it can be useful
Upvotes: 2