Loading 3D objects with THREE.js and selecting specific faces

Currently, I am in the process of modifying the object loading example on the THREE.js website to enable selecting and coloring faces of the loaded objects. To guide me through this task, I have been referring to the steps provided here.

Nevertheless, as I am not utilizing THREE.geometry objects, I am facing difficulties in integrating this strategy with the obj loader code.

One aspect that is causing me trouble is applying vertexColors: THREE.FaceColors to the obj material for proper face coloring.

The current snippet of my obj loading code looks like this:

var loader = new THREE.OBJLoader( manager );
loader.load( path, function ( object ) {
    object.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh ) {
          var faceColorMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff, vertexColors: THREE.VertexColors } );
          child.material = faceColorMaterial;
          child.geometry.addAttribute( "color", new THREE.BufferAttribute( new Float32Array( 3 * 3 ), 3 ) );
          child.geometry.dynamic = true;
        }
    } );
    scene.add( object );
    targetList.push(object);
}, onProgress, onError );

In addition, here is my detection and coloring code:

var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
vector.unproject( camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
var intersects = ray.intersectObjects( targetList, true );

if ( intersects.length > 0 ) {
  var colorArray = intersects[0].object.geometry.attributes.color.array;
  var face = intersects[0].face;
  colorArray[face.a] = 1;
  colorArray[face.a + 1] = 0;
  colorArray[face.a + 2] = 0;
  colorArray[face.b] = 1;
  colorArray[face.b + 1] = 0;
  colorArray[face.b + 2] = 0;
  colorArray[face.c] = 1;
  colorArray[face.c + 1] = 0;
  colorArray[face.c + 2] = 0;
  intersects[0].object.geometry.attributes.color.needsUpdate = true;
}

Despite my efforts, when I execute the code, the object remains black, and the faces do not change color upon selection.

What modifications can I make to ensure the selected faces are colored accordingly?

Answer №1

OBJLoader is expected to provide BufferGeometry objects that do not utilize FaceColors. Instead, BufferGeometry can implement VertexColors for assigning colors to faces, but it's important to ensure the colors attribute is properly set for the BufferGeometry. If the colors attribute is present, then using OBJLoader will give you distinct vertices for each triangle.

After utilizing intersectObjects, the returned Face3 should contain references a, b, and c, likely acting as indices for both the

mesh.geometry.attributes.position.array
and the
mesh.geometry.attributes.color.array
.

var colorArray = intersects[0].object.geometry.attributes.color.array,
    face = intersects[0].face;
colorArray[face.a] = 1;
colorArray[face.a + 1] = 0;
colorArray[face.a + 2] = 0;
colorArray[face.b] = 1;
colorArray[face.b + 1] = 0;
colorArray[face.b + 2] = 0;
colorArray[face.c] = 1;
colorArray[face.c + 1] = 0;
colorArray[face.c + 2] = 0;
intersects[0].object.geometry.attributes.color.needsUpdate = true;

By following this code, a specific face can be turned red. However, please note that this method will only be effective if your geometry includes a colors attribute and your material utilizes THREE.VertexColors.

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

Fill a Bootstrap Table with information obtained from a JSON file source

My journey into the world of bootstrap and json files has hit a roadblock, and I need some help with the following issue: Here is a snippet of my code: <div class="container"> <h1 class="text text-success text-center ">Kontoauszug</ ...

Is it possible to safely remove a class instance containing a GLcontext within a react.FC State to prevent memory leaks, especially when using a "class object with THREE.js"?

I have successfully developed a react.FC() application. In this application, you have the ability to throw a bottle in the metaverse (like a message in a bottle) to be discovered in the future. The app retrieves information from an API and constructs a c ...

Scroll to the end of the main div's horizontal position instead of using offset().left

I'm struggling with an issue in my code. <script type="text/javascript"> $(function() { $('ul.nav a').bind('click',function(event){ var $anchor = $(this); /* ...

The catch-all route handler is triggered following a response being sent by a designated route handler

Currently, I am facing a peculiar issue with the routing on my Express-based server while trying to implement authentication. Here's a snippet of code that highlights the problem: app.get('/', function (req, res) { console.log('thi ...

Maximizing the performance of shader color calls

Exploring shaders with Three.js is a new challenge for me, and I'm struggling to modify some crucial code without just adjusting the RGBA values. One limitation I face is being unable to enclose it within an .html() method. My goal is to apply 10 diff ...

I would like to take the first two letters of the first and last name from the text box and display them somewhere on the page

Can anyone help me with creating a code that will display the first two letters of a person's first name followed by their last name in a text box? For example, if someone enters "Salman Shaikh," it should appear somewhere on my page as "SASH." I woul ...

NextAuth - simulating the login process of OneLogin

I've been working on setting up a local OneLogin mocked service using WireMock. Everything has been going smoothly so far, as I was able to mock most of the OAuth OneLogin flow. However, I'm facing an issue with the last part that is preventing i ...

Using JavaScript to set the value of an input text field in HTML is not functioning as expected

I am a beginner in the programming world and I am facing a minor issue My challenge lies with a form called "fr" that has an input text box labeled "in" and a variable "n" holding the value of "my text". Below is the code snippet: <html> <head&g ...

Log out of Google+ API results in an error message stating: '$apply already in progress'

After successfully implementing the signIn functionality using Google+ API in my AngularJS web app, I encountered some issues with getting the signOut functionality to work properly. Within one of my .html files (the Nav-bar), I have a function being call ...

Maximizing Database Connectivity in Azure Functions with Javascript

I'm having trouble finding clear guidelines on how to handle database connections (specifically MongoDB) in an Azure function written in JavaScript. According to a Microsoft document linked below, it's advised not to create a new connection for ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

remove CSS attribute from the JavaScript DOM properties

Can someone help me figure out what's wrong with my code? I need to remove all "link" tags with the attribute "rel = "stylesheet" Here is the HTML code I am working with: <html> <head> <title>teset</title> <meta charset="u ...

What steps do I need to take to ensure that Phaser implements modifications made in my game.js file?

I recently completed the Phaser Tutorial and set up my project with an index.html file and a game.js file, along with downloading the phaser.min.js file. All files are located in the same folder. Although I have connected everything correctly and the outp ...

Tips on sending checkbox data as an array to a PHP script using jQuery and AJAX

I am working with a set of checkboxes like so: <input type='checkbox' name='name[]' value='1' /> <input type='checkbox' name='name[]' value='2' /> <input type='checkbox' ...

What steps do I need to take in order to activate the server-side console logging?

Recently, I created some server middleware in my api/index.js file: module.exports = function(req, res, next){ console.log(req); next(); }; After that, I integrated it into my nuxt.config.js: serverMiddleware: [{path: 'stocks', handler ...

Utilize the functionName() method within a different function

There is a function this.randomNumber() that produces a random number like 54851247. The task at hand is to access this function within another function. console.log(this.randomNumber()); // Output: 54851247 function anotherFunction() { console.log(t ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...

Leveraging Toaster Notifications in AngularJS for Custom Exception Management and Logging

Implemented the use of AngularJS Toaster for effective notification handling. To customize exception handling, set up in index.html as shown below <toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast ...

Begin the initial function again once the second function has been completed

I have 2 functions in my code: function DisplayAltText(){ var CurrentPhoto = $("#DisplayPhoto img").attr("src"); if( $.browser.msie ) { IECurrentPhoto (CurrentPhoto); } if ($(".PhotoGallery img[src='" +CurrentPhoto+ "&a ...

What steps are involved in verifying the data stored in the database?

I need help setting up authorization in PHP. Although I'm not very familiar with it, I have been tasked with implementing this feature. I want the authorization process to occur when a user clicks on a button and then redirect them to another page. I ...