Switching from a basic material to a complex multi-material in three.js during runtime

r65

Hello,

I am trying to switch from using a simple material to multi-material at runtime, but I am facing some difficulties. Could it be that I am overlooking something obvious?

Below is the test code I am working with (you can also view it on jsfiddle: http://jsfiddle.net/plotnik/8RtTy/3/). Initially, a simple material is assigned to the object, and then after the render() call, I attempt to assign a multi-material to simulate a runtime substitution.

var geom = new THREE.CubeGeometry(1, 1, 1);

var materialSimple = new THREE.MeshLambertMaterial({color: 0x020202});

// Multi-color 
var materialMulti = new THREE.MeshFaceMaterial([
    new THREE.MeshLambertMaterial( { color: 0xff0000 }),
    new THREE.MeshLambertMaterial( { color: 0xffff00 }),
    new THREE.MeshLambertMaterial( { color: 0xffffff }),
    new THREE.MeshLambertMaterial( { color: 0x00ffff }),
    new THREE.MeshLambertMaterial( { color: 0x0000ff }),
    new THREE.MeshLambertMaterial( { color: 0x000000 })
    ]);

var mesh = new THREE.Mesh(geom, materialSimple);

scene.add(mesh);

var render = function () {
    requestAnimationFrame(render);

    mesh.rotation.x += 0.01;
    mesh.rotation.y += 0.01;

    renderer.render(scene, camera);
};

render();

// Switching to multi-material
mesh.material = materialMulti;
mesh.material.needsUpdate = true;

The code does not behave as expected. It seems that only materialMulti[0] (red color) is assigned to the entire mesh.

Your assistance in resolving this issue would be greatly appreciated.

Answer №1

Modifying materials dynamically in WebGLRenderer can present challenges. For further information on this topic, refer to the Wiki article How to Update Things with WebGLRenderer.

In your specific scenario, employing MeshFaceMaterial consistently allows you to achieve desired effects by altering material colors as needed.

UPDATE: Note that MeshFaceMaterial has become obsolete and it is now recommended to directly pass an array of materials to the Mesh constructor like so:

var mesh = new THREE.Mesh( geometry, materials_array );

Version three.js r.91

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

Tampermonkey script encounters the error message "targetNode.dispatchEvent is not a recognized function"

I am attempting to press a button with Tampermonkey but keep encountering this error: userscript.html?id=2514f475-79e4-4e83-a523-6fef16dceeaa:10617 Uncaught TypeError: targetNode.dispatchEvent is not a function at triggerMouseEvent... Check out my scri ...

Troubleshooting issues with ember-data's belongsTo relationship

I am facing an issue with the model I have: Whenever I make a call to this.store.find('history'); A request is sent to http:://www.example.com/api/histories/ and I receive the following JSON response: { "tracks":[ { "id":83, ...

What is the method to activate/deactivate a button depending on a specified input value?

A simple application features an input field for a URL and a button. Upon clicking the button, the JavaScript code within it replaces the domain of the entered URL with a new domain. For instance, if a user enters "www.old.company.com/products," the appl ...

Is there a way to access the current $sce from a controller?

One way to access the current $scope outside of a controller is by using the following code: var $scope = angular.element('[ng-controller=ProductCtrl]').scope(); Is there a way to retrieve the $sce of the current controller? ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Displaying local time alongside global time using PHP

I have a challenge - I am storing time in DATETIME format and now I need to display it in the local timezone. Does anyone know how to achieve this using PHP? ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...

Postgres.js Date Range query failing to fetch any results

Recently, I have been utilizing the Postgres.js npm module to interact with a PostgreSQL database Below is the code snippet for executing the query: let startDate = '2020-01-28 08:39:00'; let endDate = '2020-01-28 08:39:59'; let table ...

Controlling JavaScript Text Opacity on Scroll: Smooth Transitions from Invisible to Visible to Hidden

I am attempting to replicate the Apple Airpods page, including its animation. I have successfully implemented the animation and now I am working on rendering text while scrolling. The text appears correctly but I'm facing an issue with opacity transit ...

Guide on traversing and modifying properties within a intricate JSON structure using Node.js

Is there a way to update the value of "message" for "chatTemplateId":"5" and "mid":"b" to "Test2" in the JSON data below using node-js/javascript? In C# I would have used LINQ, but I'm not sure how to achieve this in an optimized manner in JavaScript/ ...

Prevent input from being cleared when selecting an option with React-Select

Unfortunately, there was no satisfactory solution to this question so I will provide an answer: The issue arises when trying to utilize React-Select with a persistent input value that remains even after selection or blurring. Regrettably, this functionali ...

Uncovering design elements from Material UI components

The AppBar component applies certain styles to children of specific types, but only works on direct children. <AppBar title="first" iconElementRight={ <FlatButton label="first" /> }/> <AppBar title="second" iconElementRight={ <di ...

Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to ...

chaotic telerik editor arrangement

I have incorporated the Rad Editor into my ASP.NET page. <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <telerik:RadEditor ID="reSummery" runat="server" > </telerik:RadEditor> Despite not referencing ...

Retrieve the index of a v-for loop and then send it as a parameter to a specific function

When working with a select element generated by a v-for loop in Vue, it is important to be able to retrieve the index of the selected option. This way, you can use that index in a function for further processing. However, I have been struggling to achieve ...

The clear text button is malfunctioning and not resetting the search input as intended

I'm currently working on a filterable search form that displays images in a grid based on the search input. Everything is working smoothly - the grid resets when I delete text from the search input field. However, I've encountered an issue with t ...

Choose-option "No entries found for that specific query"

Looking for help with setting up a voting function. The vote.js script seems to be working fine, but I'm unable to get the object. Any suggestions? It appears that the POST request is not being sent. Thank you. Encountering this error: Page not foun ...

Leveraging the "dialogclose" event within jQuery Mobile

Is there a way to change an image once it is clicked and change back when the dialog it links to is closed? I found a potential solution on this site, but after modifying it for my needs, it doesn't seem to work. Can anyone help me figure out what I a ...

The fitBounds() method in Google Maps API V3 is extremely helpful for adjusting

I am trying to display a map on my website using this code: function initialize() { var myOptions = { center: new google.maps.LatLng(45.4555729, 9.169236), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: true, mapTyp ...