ThreeJs applying distinct materials to individual faces of a cube

Currently, I am facing an issue while loading a cube object exported from Blender using GLTFLoader. My attempt to apply color on each face of the cube using the addGroup method is not yielding the expected results.

The image below showcases the output that I am currently getting:

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

You can download the model from the following link: https://github.com/SourceCodeZone/3D/blob/master/Cube/test.glb

I found guidance in the answer provided here about BufferGeometry and rendering groups of faces. Below is the code snippet that I have been working with:


var cube;
var loader = new THREE.GLTFLoader();
loader.load(
    './Model/GLTF/test.glb',
    function ( gltf ) {
        gltf.scene.traverse( function ( node ) {
            if(node.isMesh){
                if(node.name==="Cube")
                    cube = node;
            }
         });
        scene.add(cube);

        var materials = [
            new THREE.MeshBasicMaterial( { color: 0xff0000 } ),
            new THREE.MeshBasicMaterial( { color: 0x00ff00 } ),
            new THREE.MeshBasicMaterial( { color: 0x0000ff } ),
        ];  
        var geometry = cube.geometry;
        geometry.clearGroups();
        geometry.addGroup( 0, 4, 0 ); // first 4 vertices use material 0
        geometry.addGroup( 4, 4, 1 ); // next 4 vertices use material 1
        geometry.addGroup( 8, Infinity, 2 ); // remaining vertices use material 2
        cube.material = materials;

    },
    function ( xhr ) {
        console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
    },

    function ( error ) {
        console.log( 'An error occurred---' +error);
    }
);

Answer №1

It seems that the BufferGeometry.groups function operates in a unique manner. Your box geometry contains 24 vertices and 36 indices, with each triangle requiring three indices. As a result, there are a total of 12 triangles (which aligns with the six sides of a cube, each composed of two triangles).

In the context of Groups data, vertices are referenced for non-index geometries, while indices are used for indexed geometries. For example, if you intend to assign three materials to your cube (one material for every two sides), the coding structure would be as follows:

var geometry = object.geometry;
geometry.clearGroups();
geometry.addGroup( 0, 12, 0 );
geometry.addGroup( 12, 24, 1 ); 
geometry.addGroup( 24, 36, 2 );
object.material = materials;

Explore a live demonstration:

Using three.js version R108

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

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

The CustomValidator ClientValidationFunction will only activate on the second or subsequent submission if CheckBoxList is checked

I am encountering an issue with a user control that is dynamically added to pages on DNN. The user control is built on a customized version of CheckBoxList and includes a CustomValidator with ClientValidationFunction set to a javascript function. It works ...

When utilizing document.addEventListener in JavaScript, Firefox fails to report exceptions triggered by DOMContentLoaded

I'm developing an internal framework that must be independent of any external dependencies such as jQuery. I'm working on implementing a custom DOM ready-style functionality, where callbacks in the ready queue should continue executing even if an ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Exploring the Distinctions Among Express Router, Module Export, and App.Use() in Node and ExpressJS

I am working with app.js, where the code looks like this: var express = require('express'); var report = require('./routes/Report'); var app = express(); app.use('/api/appReport', report); app.listen(3000); module.exports ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Vue.js - The $parent property is not accessible when a child component is nested within a <transition> element

Request: I need help with a situation involving two components, the parent component (Wall.vue) and the child component (PostItem.vue). Each PostItem includes a delete button. Upon clicking this button, a request is sent to the API to delete the item from ...

What is the process for changing the name of a key in a MongoDB response

I am reviewing the following code snippet: // retrieve a specific question app.get('/:id', (req, res) => { Question.findById(req.params.id, function(err, response){ if (err) { return res.status(404).send(); } ...

Hiding fields based on radio button selection in Prestashop checkout using jQuery

Currently, I have 2 radio buttons and several fields on my checkout page. This is what I want to achieve: - When the "delivery to address" radio button is selected, I want to display fields for address1, postcode, and city while hiding the id_state field. ...

Increments arrays in JavaScript utilizing Node.js and MongoDB

I am in the process of retrieving data from a MongoDB database using Node JS in order to create a graph at a later stage. My main objective is to gather all entries based on the hour of the day. Within my collection, there is a "created_at" field that sto ...

Steps to update the color of checkbox labels

I'm struggling with changing the colors of checkbox values based on their status - when checked, I want the text to display in green, and when unchecked, I want it to be red. Below is a sample input type, but I can't figure out how to style the t ...

Rows that have been removed from an HTML table remain within the ReactDOM

After diving into JavaScript three months ago, I recently began learning React.js just two days back. While creating a simple TODO app, I noticed that when deleting a row, it disappears from the DOM but not from the React DOM. Can anyone shed some light ...

I noticed that the node_modules folder has mysteriously vanished from my

When I tried running npm install in the terminal of VS Code. PS D:\work\backEnd> npm install npm WARN old lockfile npm WARN old lockfile The package-lock.json file was created with an older version of npm, npm WARN old lockfile so ...

Assigning specific class names to elements within an array using JavaScript

Currently, I'm attempting to assign a unique className to option elements within a select element by utilizing a conditional if statement. The goal is to apply one class name to the first half of the array and a different class name to the second half ...

Extract information from XML data and convert it to JSON format

Having trouble extracting data from a parsed XML to JSON. I can't seem to figure out how to get the data properly displayed on my screen. Can someone guide me on the right approach? Here is the Formatted JSON Data: { "event":[ { ...

Encountered an error: Unable to access the property 'getTotalLength' from a null value

My SVG animation was functioning perfectly on CodePen. However, when I integrated it into my website, it suddenly stopped working. The console displayed the following error message: Uncaught TypeError: Cannot read property 'getTotalLength' of n ...

Implementation of async operations using while loop in Node.js

I'm facing an issue with my code snippet. Here's what it looks like: Rating.find({user: b}, function(err,rating) { var covariance=0; var standardU=0; var standardV=0; while (rating.length>0){ conso ...

Anchor tags are not visible to Jquery

My issue is with integrating JQUERY and PHP. In my external PHP file, I have the following echo statement - `echo ("<a href='#' id='bb'>hello</a>"); Similarly, in my external js file, I have this JQUERY code - $(' ...

Attempting to retrieve div measurements in vh/vw units rather than pixels

I'm currently working on an app where I want the divs to be resizable. In order to achieve this, I need to store the user's changes in my database. My main concern is how can I convert the units provided in pixels (px) to a different unit of mea ...

Unable to generate StumbleUpon traffic for a URL through AJAX due to the API returning text/plain

I'm attempting to acquire StumbleUpon views for a specific URL using $.ajax. This is the API I am utilizing: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://example.com/ Here is the complete code snippet: $.ajax({ type: "GET ...