Identify mesh interaction on a 3D model

I have successfully loaded a model in from .obj and .mtl files. My goal is to allow the user to interact with specific parts of the model, such as changing their color by clicking on them. For example, clicking on a door of a car should enable the user to change the color of that door mesh.

Below is the code I used to load the model:

var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setPath('Models/Aventador/');
    mtlLoader.load('Avent.mtl', function (materials) {
        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials(materials);
        objLoader.setPath('Models/Aventador/');
        objLoader.load('Avent.obj', function (object) {
            object.position.y = 0;          
            scene.add(object);
        }, onProgress, onError);
    });

UPDATE: I have now implemented the following code, which does not show any errors and prints 'mouseup' to the console as expected. However, it does not detect any intersections as intended. Any thoughts on what could be causing this issue?

var mouse = new THREE.Vector2();
function onDocumentMouseUp(event) {
    console.log("mouseUp")
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    var raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObjects(scene.children);
    for (var i = 0; i < intersects.length; i++) {
        console.log(intersects[i]);
        intersects[i].object.material.color.set(0x0000ff);
    }
}

UPDATE 2: https://i.sstatic.net/AY7yr.png

Answer №1

To handle the clicking functionality, you should utilize raycasting to determine the intersection point between the model and the mouse's position. To get started, refer to the link provided below for more information:

Raycaster

Once the raycast identifies the object that was clicked, you can store this object for future use, such as changing its color properties.

In response to your second inquiry, the objects array functions similarly to the scene.children demonstrated in the aforementioned link. You could provide just the mesh to it and verify if the raycast intersects with it (as opposed to other elements like lights or planes on which the car model might be positioned).

Update: As you were dealing with an Obj file, our conversation revealed that enabling recursion on the raycast was crucial to accurately detect the specific parts of the loaded model. The process described in this answer helped address this issue.

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

In Reactjs, the specified property title is not found within the string type

Currently, I am working with Reactjs and using the nextjs framework. I have encountered an issue while fetching data where I am receiving an error message stating "Property 'title' does not exist on type 'string'". How can I r ...

Is there a way to determine the file size for uploading without using activexobject?

Can the file size of an uploading file be determined using Javascript without requiring an ActiveX object? The solution should work across all web browsers. ...

Displaying Data in a Table

In my current setup, I have a table that receives data from a form through JavaScript. The code is as follows: <div class="row"> <div class="span*"> <table id="production" class="table table-bordered" style="margin:10px auto;bor ...

What is the best way to reverse an EJS forEach loop?

Here is my ejs code to display images and names from my database. How can I reverse the array order to show the images and names in reversed order? <% posts.reverse().forEach(function(post){ %> <div class="col-md-3 col-sm-6"> ...

What is the best way to confirm the invocation of super in sinonjs?

My JavaScript/TypeScript class (AAA) extends another class (BBB). The API of class BBB is stable, but the implementation is not yet finalized. I just want to unit test some functions in class AAA. However, I'm facing an issue in creating an instance o ...

Ways to control the number of function invocations in an AngularJS controller

I am facing a challenge where data is being fetched from multiple controllers, causing functions to hit the server more than fifty times until they receive a response. I am unsure how to handle this situation effectively and would appreciate some guidance. ...

The issue with JQGrid: Inaccurate selection of drop down value when edit type is set to 'select'

I am currently using JQGrid 4.4.4 and have encountered an issue with a column set to edittype = 'select'. While the value displayed in the grid row is correct, the drop-down or combo-box value is being set to the wrong value when editing the row. ...

What steps can I take to ensure that my initial Ajax Get request is completed before proceeding with the next one?

Having two methods that return promises is not enough. I am attempting to make the second method execute only after the first one has obtained and manipulated data, but I have struggled to find a solution despite others asking this question before me. Here ...

The latest update to the Server Stats code mistakenly changes the channel to "undefined" instead of displaying the total number

I've been working on a private bot for a specific server that displays server statistics and more. However, I've encountered an issue where every time a user joins or leaves the guild, the bot updates a channel with 'undefined' instead ...

AngularJS: Struggling to Set Up Controller

I recently started my journey with AngularJS a few days back, and I've encountered this frustrating issue. Every time I run into this error: Error: ng:areq Bad Argument Argument 'NewStudentCtrl' is not a function, got undefined All my ot ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...

To remove, simply double-click on the jQuery duplicate element

I am looking to implement the feature of deleting a cloned helper object by double-clicking on it. Below is the javascript code I currently have: $(document).ready(function(){ $(".draggable").draggable({ helper: 'clone', sta ...

Extract the JSON value from a JavaScript variable using the index value function

Is there a way to modify the index value function to fetch the gb value of the "see": 8 variable within the "val": "West" group? Could utilizing an array be a solution for this scenario? Although the correct value for the gamesBack of the val.see == 8 is ...

Exploring Clara.io's json data for 3D geometry within the Three.js

I've encountered an issue with exporting models in Clara.io. According to their instructions, exporting a selection should create a file for JSONLoader and exporting the full scene should result in a file for ObjectLoader. However, none of the export ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

Implementing popup alert for multiple tabs when Javascript session times out

I have implemented javascript setInterval() to monitor user idle time and display a popup alert prior to automatic logout. However, it seems to be functioning correctly only in single tabs. Here is the code snippet: localStorage.removeItem("idleTimeValue ...

Retrieve JSON data from an HTTP request using Node.JS

Hi there, I'm struggling with the Node.js HTTPS request. Basically, I send a request to a server and it responds with a JSON message that I need to parse and save in a variable so I can use it in other functions. let obj=JSON.parse(response); return ...

Dynamically showcasing content in an HTML table

Having trouble with this code snippet. It's supposed to iterate through array objects and display them in an HTML table. The third row should have buttons, but nothing is showing up. Can you spot the issue? Here's the HTML code: <html> & ...

Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class= ...

Display a page with sections that have opacity applied, identified by the hashtag #section, and utilize JavaScript to automatically scroll to the top of

Check out my app at . I'm working on overriding the scroll bar behavior in CSS to keep the entire app visible, including the logo, header, and controls, as users navigate through different sections. However, I seem to be having trouble with the CSS as ...