Displaying a randomly selected texture using three.js

If I have 10 objects and I want to assign a randomly selected texture from a pool of 10 textures to each object, how can I achieve this for a mesh object?

for(let i = 1; i <= 10 ; i++)
  { let loader = new THREE.TextureLoader();
    let randomTextureIndex = Math.floor(Math.random() * 10) + 1;
    let testMat = new THREE.MeshPhongMaterial({ map: loader.load('images/image' + randomTextureIndex) });
    let testGeo = new THREE.SphereGeometry(50, 50, 50);

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

Answer №1

If you have a series of texture-images with numbered filenames, you can use the following code snippet:

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

In case your texture-images do not follow a numeric sequence, you can create a list of filenames and randomly select one to use:

var texturesList = [
    'images/image1',
    'images/another-image',
    'images/yet-another-one',
    ...
    'images/tenth-image'
];
...
...
var randomIndex = THREE.Math.randInt(0, texturesList.length - 1);
var randomTexture = loader.load(texturesList[randomIndex]);
var exampleMat = new THREE.MeshPhongMaterial({ map: randomTexture });
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Object.create allows for the creation and sharing of methods for each instance without compromising memory efficiency

Here's an example code snippet where I am trying to understand Object.create: function Animal {} var cat = new Animal(); I have a requirement to create 100 animals and add a method called saySomething() to the constructor. To achieve this, I add the ...

No content returned with 200 status code in response to ajax post request specifically on a mobile browser

Just want to say thank you in advance. I tried searching online for a solution to this issue, but couldn't find anything that worked. Currently, I am working on a web application using vue.js for the front end and AWS Lambda functions with API Gateway ...

Updating documents in MongoDB periodically at specified intervals

I have developed a unique "lowest bid auction" system where users can set a base price, a price drop amount, and a price drop interval. For instance, if a user sets the base price as $1000, price drop amount as $100, and price drop interval as 1 hour, the ...

Passing hooks down in React leads to input losing focus due to rerendering

I have a parent component where I initialize some state, and then pass it down to the child components for updating. Unfortunately, when the update occurs, the component tree is re-rendered causing my inputs to lose focus. Even adding a `key` did not resol ...

What could be causing the hover effect to not work on other elements within the div?

I am working on creating a card that displays only the image when not hovered, but expands and reveals additional information in a div to the right of the image when hovered. Unfortunately, when I hover over the image and then move towards the adjacent div ...

The image located at 'http://localhost:8080/favicon.ico' was unable to load due to a violation of its content

I am currently developing a JavaScript app called food2fork. I encountered an issue when the AJAX call API promise is fulfilled and the results (recipes) are rendered. However, when I click on one of the recipes, it moves to the next page and displays: ...

Utilize the map function on an array object to present data in a table using React framework

My parent component passes an array object that looks like this: https://i.sstatic.net/Nqh81.png I want to organize these values into a table with the keys in one column and their corresponding values in other columns. The desired format is shown here: ht ...

directive encapsulating basic functionality

I'm currently working on creating a directive that can sort any type of data at any point within my application. Let's take a look at the code snippet below (which is based on actual code, but simplified for clarity): angular.module('test&a ...

Trouble with two dropdown selections in Angular and preset values

I am encountering an issue with a select input in angular 7. The scenario involves having 2 selects where selecting an option in the second select populates the corresponding values in the first select. The first select should display a default placeholder ...

Folding without extending

My button has a div inside it with content. I've set it up so that when the div is clicked, the collapsed content expands. The hover effect changes color and pointer as expected. But for some reason, clicking on the div doesn't expand the content ...

React.js - Add a new row div when reaching a limit of X items to keep the layout

Currently in the process of learning React.js. Here is the code snippet I am working with: const items = Object .keys(this.state.items) .map(key => <Item key={key} details={this.state.items[key]} />) ; return ( <div className ...

Develop a program using the local time of Barcelona as a reference

I'm having trouble with my code that is supposed to change the background and image based on the current hour in Barcelona. It doesn't seem to be working properly. JAVASCRIPT CODE var now = new Date(); var offset = now.getTimezoneOffset(); var ...

Access a file from the local system using JavaScript within a Django application

I am encountering an issue with fetching a .txt file in a folder using the fetch() function in JavaScript within a Django project. Whenever I try to call the file with fetch, a Django error occurs. (index):456 GET 404 (Not Found) The file I am trying to ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

What is the best way to establish a maximum value for variable inputs?

In my Vue form, I have dynamic inputs for issuing shares to shareholders. The user first registers the total amount of shares in the form, then starts issuing this total amount partially by adding dynamic inputs as needed. Finally, the form is submitted. M ...

What could be the reason why readyState is not equal to 4?

I've been trying to figure out how to use Ajax to fetch data from a database, but I'm encountering some issues... The problem arises when I submit the query and nothing appears on the screen... I understand that this issue is related to the read ...

When a user clicks on an anchor tag, close the current window, open a new window, and pass the

I have a scenario where I have an anchor tag that triggers the opening of a window on click. In this newly opened window, there is a table with a column containing another anchor tag. Here is what I am trying to achieve: Code for the anchor tag: functio ...

Converting Mesh to Object3D: A step-by-step guide

Currently utilizing Typescript alongside Webpack. To create a 3D floor using three.js, I have integrated multiple plane objects (100 in total) with a seamless image serving as their background: import { Scene, PerspectiveCamera, WebGLRenderer, ...

What is causing the "X" to not appear behind the see-through square?

Here is a snippet of code displaying two rectangles with "X"s behind a transparent rectangle. The top rectangle has a reddish background where the "X" shows through as intended. However, the bottom rectangle has a default transparent background causing the ...

What is preventing Angular from loading on this Plnkr?

I've spent time researching my problem and testing various solutions, but I still can't seem to resolve it. Angular doesn't appear to be loading correctly in Plunker for some reason. I've heard that ng-app is no longer supported in ne ...