Zhyohzhy Zhyohzhy - 1 month ago 17
Javascript Question

Loading a random texture in three.js

Suppose I have 10 objects and I want for each object to be given a texture picked for me randomly out of a pool of 10 textures. How do I go about that for this mesh object?

for(var int = 0; int <= 10 ; int++)
{ var loader = new THREE.TextureLoader();
var testMat = new THREE.MeshPhongMaterial({ map: loader.load('images/image1') });
var testGeo = new THREE.SphereGeometry(50, 50, 50);

testSphere = new THREE.Mesh(testGeo, testMat);
testSphere.position.set(distance, 100, 100);
scene.add(testSphere); }

Answer

Assuming all of your texture-images are named in a numeric/sequential manner, you could do:

...
var testMat = new THREE.MeshPhongMaterial({ map: loader.load('images/image' + THREE.Math.randInt(1, 10) ) });
...

If not, then you'd make a list of filenames in a manner similar to this, and choose a random value from the list:

var texturesList = [
    'images/image1',
    'images/some-other-image',
    'images/yet-another-image',
    ...
    'images/10th-image'
];
...
...
var randIndex = THREE.Math.randInt(0, texturesList.length - 1);
var randTexture = loader.load(texturesList[randIndex]);
var testMat = new THREE.MeshPhongMaterial({ map: randTexture });
...