Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material:

Class declaration and constructor for Mesh TypeScript file (excerpt from ThreeJS source code):

export class Mesh<
    TGeometry extends BufferGeometry = BufferGeometry,
    TMaterial extends Material | Material[] = Material | Material[] // ### Here: Material[] ###
> extends Object3D {
    constructor(geometry?: TGeometry, material?: TMaterial);

Here lies the issue that I'm struggling to resolve... When applying a single Material, my Mesh renders correctly. However, when attempting to use two materials within an array, my Mesh does not display. Moreover, there are no error messages appearing in the console during rendering.

My main objective is to assign separate materials for the inner and outer parts of my object. https://i.stack.imgur.com/D4wMD.png


Below is my code snippet:

export function init(radius: number = 18.0, innerColor: number = 0xFFFFFF, outerColor: number = 0x444444) {
    var obj = new Object3D();
    loader.load(
        objPath, 
        function(object){
            obj = object;
            const mesh = obj.children[0] as Mesh;
            // WORKING:
            mesh.material = new MeshPhongMaterial({color: outerColor});
            // NOT WORKING: Using two materials
            // mesh.material = new Array<Material>(new MeshPhongMaterial({color: outerColor}), new MeshPhongMaterial({color:innerColor}));
            mesh.scale.setLength(radius)
            scene.add(mesh);
        },
        function (error){
            console.log(error)
        }
    );
}

Why am I unable to see my object when utilizing two materials?

I am aware of the existence of MeshFaceMaterial in previous versions, and the acceptance of material arrays by the constructor is supposedly a replacement for that in some capacity.


ThreeJS version: r128

Any assistance would be greatly appreciated!

Answer №1

To easily create a mesh with two separate materials for the inside and outside, you can clone the mesh and assign different materials to each:

const outerMesh = obj.children[0] as THREE.Mesh;
const innerMesh = outerMesh.clone();

// The outer mesh displays the front side
outerMesh.material = new THREE.MeshPhongMaterial({
    color: outerColor,
    side: THREE.FrontSide
});
// The inner mesh displays the back side
innerMesh.material = new THREE.MeshPhongMaterial({
    color: innerColor,
    side: THREE.BackSide
});

// Scale down the inner mesh slightly to prevent z-fighting
innerMesh.scale.multiplyScalar(0.99);

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

What is the best way to use JavaScript in an ASP.NET Controller to navigate to a different webpage?

I'm currently developing a website using Angular 1 with an ASP.NET MVC backend. I'm trying to create a link that will gather certain parameters using JavaScript, retrieve the correct URL from a controller, and then redirect the user to a differen ...

Guide on displaying gallery images when clicking on a specific class

I am in the process of developing a gallery tab for a website, initially displaying three thumbnails. The goal is to reveal the remaining thumbnails when a class named show-all is clicked. I have successfully animated the gallery's height to show the ...

Unexpected outcomes arise when parsing headers from a file-based stream

Currently, I am in the process of creating a small parser to analyze some log files using node streams (more specifically io.js). I have been referring to the documentation for unshift to extract the header. While I can successfully divide the buffer and ...

Components loading in Angular result in lat long being undefined in google map integration

I am currently utilizing Ionic-angular AGM. I am facing an issue where I am unable to retrieve my current location when the component loads, as it seems like the component is being fired before the latitude and longitude are ready. How can I make this proc ...

Troubleshooting: AngularJS ng-repeat not rendering JSON data

I have successfully retrieved JSON data from a database using PDO in Angular. The data is being returned as expected when I encode it to JSON. However, I am facing an issue with displaying the data using ng-repeat in Angular. Although the div elements are ...

Is it possible for JavaScript to style two different phone number elements on a single page?

After successfully creating a script that auto formats an element by ID on my website, I encountered an issue with multiple forms. The script works perfectly for a single element, but when I attempted to change it to target elements by class name using get ...

Merge the data from various sections of a JSON object into a unified array

Upon completing an ajax call to a specific URL, I receive data in the form of a JSON object structured like this: {"field1":["val1","val2","val3",...,"valn"], "field2":["vala","valb","valc",...,"valx"]} My goal is to merge the values of field1 and field ...

Looking to incorporate HTML5 videos into a responsive Bootstrap carousel?

I've been working on creating a carousel that includes videos. When it comes to images, everything works smoothly as they are responsive even in mobile view. However, I'm encountering an issue with videos where the width is responsive but the hei ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

React Typescript can easily differentiate between various prop types by selecting either of the two types

I am working with two Typescript interfaces: type ISecond = { timeType: string secondTime: number } type IDay = { timeType: string startTime: number endTime: number } When it comes to my react function props types, ... const CountDown ...

Unable to retrieve data following a promise in Ionic 3

Hello, I'm currently working on an Ionic application that needs to display data in a Form Group after retrieving it with a SOAP ReadData request. Although I call my function and try to display the data in the form, there seems to be an issue as the f ...

Having trouble getting the Bootstrap tooltip to work on a Select option?

Is there a way to have a tooltip displayed for each option in the select box? <select ng-model="rightList" class="form-control" size="13" multiple> <option ng-repeat="item in selectedList" value="{{$ ...

Transmitting a multidimensional array in JavaScript to an AjaxPro method on a front-end webpage: A step-by-step guide

Imagine a scenario where I have a C# method that requires an array parameter: [AjaxPro.AjaxMethod] public int Test3(string[,] array) { return array.Length; } Next, I define a multidimensional array on the front page using JavaScript: var array = ...

Encountered an unforeseen token "<" that is causing the server to return a 404 HTML page instead of the intended .js

I am currently developing a to-do list application using Node.js Express and EJS. In the app, I have implemented a filtering functionality with a URL path of "/filter/query". Based on the selected category (either "lists" or "lastupdated"), the app filters ...

Updating the value of an HTML table cell when the data in local storage is changed using JavaScript

In my JavaScript code, I have a function that retrieves data from an API and stores it in the browser's localStorage. The API fetches ETA data and saves it in localStorage using the key id_ETA (e.g., 12342_ETA). I want the values in the HTML table&a ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

What is the best way to retrieve the coordinates of a specific point from a BoxGeometry object?

In a unique scenario, there lies a customary BoxGeometry whose measurements are aligned with a collection of entities. Is it possible to determine the precise location of a specific point within this BoxGeometry (x:1, y:1, z:1), in relation to the entire ...

My Next.js application is successfully making Axios API calls to my localhost while running on the server-side

In my Next.js and React application, I am utilizing the axios library. Initially, I was able to successfully call the API from the server using getStaticProps() and render the initial data properly. However, when attempting to fetch more data from the clie ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...