Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to read data[0] which is 49, and the second material object [cubeMaterialTwo] to read data[1] which is 7.

Check out my code snippet below:

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d6cad0c7c7e2928c93939a8c91">[email protected]</a>/build/three.js"></script>

let scene, camera, renderer;

let cubeGroup;

init();
animate();

function init() {

const data = [
[49, 7]
]

var i = 1;

width = 500
height = 500
fov = 9
aspect = 1/5
near = .1
far = 1000

loader = new THREE.TextureLoader()

scene = new THREE.Scene(); // ADDED

camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(50, 30, 50);
camera.lookAt( scene.position );


cubeGeometries = data.map(row => {
 return row.map(c => {
  return new THREE.BoxBufferGeometry(0.2, c / 8, 0.2);
 })
})

var materialArray = [];

const cubeMaterial = new THREE.MeshBasicMaterial({
 map: loader.load('../path/to/.jpgOne')
});
cubeMaterial.color.convertSRGBToLinear();

const cubeMaterialTwo = new THREE.MeshBasicMaterial({
map: loader.load('../path/to/.jpgTwo')
});
cubeMaterialTwo.color.convertSRGBToLinear();

materialArray.push(cubeMaterial, cubeMaterialTwo);

const cubeMeshes = cubeGeometries.map(row => {
  return row.map(cubeGeometry => new THREE.Mesh(cubeGeometry, materialArray))
})

cubeGroup = new THREE.Group();
 data.forEach((row, i, iarr) => {
  row.forEach((d, j, jarr) => {
   cubeMeshes[i][j].position.set(
    i / iarr.length - 0.5,
    d / 8 * 0.5 - 0.6,
    j / jarr.length - 0.5);

   //cubeMeshes[i][j].scale.set(1,4,1);
   cubeGroup.add(cubeMeshes[i][j]);
  })
 })

const mainLight = new THREE.DirectionalLight(0xffffff, 5.0);
 mainLight.position.set(10, 10, 10);

const ambientLight = new THREE.HemisphereLight(0xddeeff, 0x202020, 3);

var material = new THREE.LineBasicMaterial({
 color: 0x0000ff
});

scene.add(cubeGroup);
scene.add(mainLight);
scene.add(ambientLight);


renderer = new THREE.WebGLRenderer({
  antialias: true
});

renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.physicallyCorrectLights = true;

document.body.appendChild(renderer.domElement); 

}

function animate() {
 requestAnimationFrame( animate );
 cubeGroup.rotation.y += 0.005;
 renderer.render( scene, camera );

}

Answer №1

After making a slight adjustment to your code, I noticed that both textures are being loaded, but they are being applied to the meshes in opposite positions. This is because you are passing the entire materialArray to the Mesh constructor. I have replicated the issue in a fiddle showcasing both textures using your code.

  const cubeMaterial = new THREE.MeshBasicMaterial({
    map: new THREE.TextureLoader().load('https://i.postimg.cc/25m7H09s/metal1.jpg')
  });
  cubeMaterial.color.convertSRGBToLinear();

  const cubeMaterialTwo = new THREE.MeshBasicMaterial({
    map: new THREE.TextureLoader().load('https://i.postimg.cc/pXs9NqTN/OIP.jpg')
  });
  cubeMaterialTwo.color.convertSRGBToLinear();

It seems like your intention was to load a texture for each mesh, but the TextureLoader is loading both textures regardless. https://i.sstatic.net/HeTk5.png https://i.sstatic.net/Io6RN.png

If this answer addresses your original question, please mark it as "answer accepted" to help others who may have the same issue.

EDIT: I have updated the fiddle showcasing both textures with a random selection for each object. Feel free to test it multiple times to see it in action.

  return row.map(cubeGeometry => new THREE.Mesh(cubeGeometry, materialArray[Math.round(Math.random())]))
  })

https://i.sstatic.net/TJyX1.png

EDIT 2: I have resolved the issue you mentioned, where each block requires a different texture. I have provided a new fiddle, and you just need to replace the relevant code with these lines.

  let index = 0;
  const cubeMeshes = cubeGeometries.map(row => {
    index++;
    return row.map((cubeGeometry, index) => new THREE.Mesh(cubeGeometry, materialArray[index]))
  })

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

Using HTML5 Canvas: Implementing an Image.onload() function through Image.prototype

I am trying to create a simple function that will refresh the canvas automatically when an image is loaded. The idea is to be able to use code like this: var map = new Image(); map.onloadDraw(); map.src = "images/" + worldmapCanvasShapeImage; Currently, ...

Adjusting widths of strokes in React Native Vector Icons

I selected an icon from the react-native-vector-icon library. For instance, let's use featherIcons. How can I include a stroke-width property to the react-native-vector-icons package? import FeatherIcon from 'react-native-vector-icons/Feather&ap ...

Personalized tooltips for numerous data sets in Highcharts

I am currently in the process of constructing a highchart that is capable of accommodating up to five different types of data series. I have arranged similar series together, resulting in three distinct y-axes for the various series. However, I have encou ...

What methods can I use to insert an array of objects into a Query?

I'm currently trying to understand how I can pass an array of objects into my GraphQL query. The documentation seems a bit confusing on this matter. In my project, I am using Apollo on the frontend, Graphql-yoga on the backend, and Prisma as my databa ...

Are there any methods for simultaneously hosting both React and vanilla JavaScript websites?

I want to host a full-fledged web application that is primarily implementing ReactJS, but also contains sections utilizing vanilla JavaScript. Is it possible to host a web app that combines both React and vanilla JavaScript functionalities? (My backend i ...

The utilization of 'new' is not allowed with an expression that does not have a call or construct signature in TypeScript

While searching for a solution, I stumbled upon this link which unfortunately did not provide the answer I was looking for: Cannot use 'new' with an expression whose type lacks a call or construct signature I am facing a similar issue. In my JavaS ...

Do class bindings with variables need to be inline when using Vue 3?

Consider the following HTML: <template v-for="(child, index) in group"> <div :class="{'border-pink-700 bg-gray-100 ': selected === child.id}"> <div>Container Content</div> </div> & ...

Tips for patiently anticipating an object to undergo asynchronous modifications?

I have an array containing items, and I need to incorporate the asynchronous value from getProductMinQuantity. The issue I'm facing is that the response with res.status(200)... gets sent before modifying item.order_quantity_minimum. I had assumed us ...

Three.js: Objects in the distance appear more subtle

Currently, I am developing a three.js scenario that showcases textured point sprites. These sprites obtain their textures from a single uniform, which is a 2D canvas containing the alphabet: https://i.stack.imgur.com/Ceh9x.png In my scene, all the letter ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Utilizing jQuery and CSS to make an entire div clickable, and activate an 'a' tag hover state upon hovering

Looking to create a clickable link for the .wrapper div that directs users to the location of a.icon. Want the .wrapper div to activate the a.icon:hover state when hovered over, not just when hovering over the icon itself. Any assistance would be highly a ...

Error in react-native while attempting to find the lowest common ancestor of `responderInst` and `targetInst` using `Event

After upgrading my react-native app to version 0.44, I encountered an issue where the app would start up without any problems in both the simulator and on a mobile device. However, when I tried pressing a component like a button or widget, a red error scre ...

When attempting to deserialize a 2D array in JSON, it unexpectedly returns as a string instead of

I am trying to figure out how to deserialize the JSON string provided below into a two-dimensional array object using JavaScript. Whenever I attempt to use JSON.parse or eval, it ends up getting converted into a string format. Currently, I am utilizing D ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

The Safari browser's requestAnimationFrame is operating smoothly at 30 frames per second

I'm currently working on a basic scene that involves moving and rendering planes. The framerate of Chrome is clocked at 120 fps Whereas, Safari is only delivering 30 fps How can I balance these out to achieve consistent performance across both brows ...

Ways to halt streaming without shutting down the Node.js server

I am currently facing an issue with closing a Twitter stream, as it causes my server to crash and requires a restart. Is there a way to close the stream without affecting the Nodejs (express) server? Here is the error message I am encountering: file:///mnt ...

A cautionary alert is triggered by vsCode when analyzing seemingly correct code sourced from vue.js documentation

While using Visual Studio Code version 1.13.1V and referring to the vue.js guide on lazy loading, I encountered an issue when writing the following code snippet: import Vue from 'vue' import Router from 'vue-router' const Health = () = ...

What is the best way to insert HTML elements onto a webpage and retrieve them in an asp.net environment?

Greetings, For the past day, I've been attempting to dynamically add elements to a web page using Visual Studio and access their values. Either I'm overthinking things, being foolish, or there just isn't a straightforward way to achieve wha ...

Difficulty loading AJAX with autocomplete feature. Any suggestions?

I have created a jQuery autocomplete feature that works correctly, but when the value is removed using the Backspace key, the 'LOADING...' message remains visible instead of hiding. How can I make it so that after removing the value with the Back ...

Troubleshooting $scope.$on unit testing - event not getting detected

In one of my controllers, I have implemented a simple $scope.$on function: app.controller('MyController', function($scope) { $scope.$on("myBroadRcvr", function(event, data) { $scope.name = data.name; $scope.empID = data.empID ...