Struggling to accurately determine the intersection face vertex positions in Three.js

Hello there! I've been immersed in the world of three.js, dealing with loading models using THREE.JSONLoader. Currently, I'm faced with the task of selecting these objects and their faces, which I've managed to do successfully. Now, my goal is to retrieve the vertices of the selected face. Take a look at the code snippet below:

intersections = raycaster.intersectObjects( objects );

if ( intersections.length > 0 ) {

            if ( intersected != intersections[ 0 ].object ) {

                intersected = intersections[ 0 ].object;

                /*HERE*/
                    console.log("Hit-face a @ " + intersections[0].face.a);
                    console.log("Hit-face b @ " + intersections[0].face.b);
                    console.log("Hit-face c @ " + intersections[0].face.c);

                    var faceColorMaterial = new THREE.MeshBasicMaterial( 
                    { color: 0xffffff, vertexColors: THREE.FaceColors } );

                    var sphereGeometry = new THREE.SphereGeometry( 0.1, 32, 16 );
                    var sphereGeometryf = new THREE.SphereGeometry( 3, 32, 16 );
                    var sphereGeometrys = new THREE.SphereGeometry( 3, 32, 16 );
                    var sphereGeometryt = new THREE.SphereGeometry( 3, 32, 16 );

                    var sphere = new THREE.Mesh( sphereGeometry, faceColorMaterial );
                    sphere.position.set(intersections[0].point.x, intersections[0].point.y, intersections[0].point.z);

                    var spheref = new THREE.Mesh( sphereGeometryf, faceColorMaterial );
                    spheref.position.set(intersections[0].object.geometry.vertices[intersections[0].face.a].x + intersections[0].object.position.x,
                    intersections[0].object.geometry.vertices[intersections[0].face.a].y + intersections[0].object.position.y,
                    intersections[0].object.geometry.vertices[intersections[0].face.a].z + intersections[0].object.position.z);

                    var spheres = new THREE.Mesh( sphereGeometrys, faceColorMaterial );
                    spheres.position.set(intersections[0].object.geometry.vertices[intersections[0].face.b].x + intersections[0].object.position.x,
                    intersections[0].object.geometry.vertices[intersections[0].face.b].y + intersections[0].object.position.y,
                    intersections[0].object.geometry.vertices[intersections[0].face.b].z + intersections[0].object.position.z);

                    var spheret = new THREE.Mesh( sphereGeometryt, faceColorMaterial );
                    spheret.position.set(intersections[0].object.geometry.vertices[intersections[0].face.c].x + intersections[0].object.position.x,
                    intersections[0].object.geometry.vertices[intersections[0].face.c].y + intersections[0].object.position.y,
                    intersections[0].object.geometry.vertices[intersections[0].face.c].z + intersections[0].object.position.z);



                    scene.add(sphere);
                    scene.add(spheref);
                    scene.add(spheres);
                    scene.add(spheret);
                /*HERE*/
            }
        }

In this example, the "sphere" represents the intersection point where the Ray meets the 1st object.

The visual elements spheref, spheres, and spheret are used for visualizing the vertices. However, when I add these spheres to those vertices, they appear misplaced.

This method works with the provided example, but when applied to loaded objects, it seems to encounter issues.

If you're interested, you can explore this alternative code sample, replacing the onDocumentMouseDown event with the snippet above:

While promising, this method is not entirely compatible with loaded objects.

Answer №1

Ensure that you are applying the WorldMatrix of the object to your points.

Here is a step-by-step guide on how to achieve this:

Begin by obtaining the face Point of the original mesh, like so:

PointA = intersections[0].object.geometry.vertices[intersections[0].face.a]

This point does not undergo scaling, rotation, or translation. To adjust the position correctly, you must incorporate these transformations. To do so, utilize the WorldMatrix of the Object on the Point.

PointA.applyMatrix4(intersections[0].object.matrixWorld); 

At this stage, you now possess the accurate coordinates for placing your spheres. (PointA.x, PointA.y, PointA.z)

Answer №2

Aha! Problem solved. It turned out the issue was with the scale setting...

Instead of adjusting the scale using myobject.scale.set( 3, 3, 3 ), I realized that the vertices coordinates were not changing. So, I decided to comment out that line and export models that are three times larger. However, if you still need to work with a scaled model, make sure to adjust the x, y, z values accordingly (where x is a number based on your scale).

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

Using Node.js, Express, and Socket.IO to establish real-time communication between two static client pages

I'm in the process of creating a remote control for a gallery using nodejs, express, and socket.io. Here's the project structure: /index.js /public/screen.html /screen.js /remote.html /remote.js The goal is to display a gallery of ima ...

Axios is unable to retrieve data in React render, but it is successful when accessed through the console

I am currently in the process of developing an e-commerce website and encountering an issue with rendering image data stored in MongoDB. The goal is to fetch the image data using axios and display it on the website. However, despite successfully fetching t ...

Refreshing a page in MVC after making an Ajax call to the controller

In my controller, I have the following code: public async Task < ViewResult > Favourites(string ids) { // API call to fetch book data if (data != null) { var bookList = JsonConvert.DeserializeObject < Book[] > (data); ...

Exchange information among unrelated components

I'm working on implementing a vue event bus to facilitate event communication between my components. In my app.js file, I have included the line Vue.prototype.$eventBus = new Vue();. Within one component, I trigger an event using: this.$eventBus.$emit ...

Tips for passing down props or all the properties of an object to create a dynamic component

I am facing an issue with a v-for loop in my project. The loop is supposed to iterate through objects in a list of todos fetched from the backend. These objects are then passed down to a child component, which displays each todo individually. However, I ha ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Display a pleasant alert message when the file is not recognized as an image during the loading

Is there someone who can assist me? I have attempted multiple times but without success. How can I display a sweet alert when a file is selected that is not an image? <input type ="file" /> ...

What is the best way to retrieve data based on conditions in React?

I'm currently learning React and trying to pass props from a parent component (table row) to a child Modal component. Inside the child component, I want to fetch data based on the props provided. I have created a custom hook called useFetch that store ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

Allowing Cross-Origin Resource Sharing on an Express Server hosted using Firebase Cloud Functions

Hey there, I have a simple Express setup on Firebase, shown below: import { onRequest } from 'firebase-functions/v2/https'; import express from 'express'; import bodyParser from 'body-parser'; import router from './router ...

Rotation Causes Vertices to Deviate from Expected Axis Movement

While moving the vertices of a shape on mouse move works well, applying a rotation to the shape causes the vertices to move along the wrong axis. If you'd like to see the issue in action, check out this codesandbox.io link: https://codesandbox.io/emb ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

Updating the route in Express.js/Node.js to redirect form submission from `/page` to `/page/<input>`.Is this fine for you

How can I redirect a user from /page to /page/:nickname in Express after they enter a nickname and click submit? This is my code: // app.js app.get("/page", (request, response) => { response.render("page"); }); app.get("/page/:nickname", (reques ...

Retrieve the title of a webpage using cheerio

I am attempting to extract the title tag of a URL using cheerio, but I keep receiving empty string values. Here is my code snippet: app.get('/scrape', function(req, res){ url = 'http://nrabinowitz.github.io/pjscrape/'; reques ...

Issue with Ionic and Angular: Struggling to empty input field

Within my Ionic app, there is a form that contains an input field and a button. Upon clicking the button, an action should occur within the controller to clear the input field. Unfortunately, this functionality is not working as expected. Despite its simpl ...

What are some ways to implement the 'charCodeAt' method within a for loop effectively?

Currently, I am working on developing a hangman game in JavaScript to enhance my coding skills. One task that I am facing is extracting the keyCode of a character at a particular position within an array. To achieve this, I have been using the 'charCo ...

What is the method for reaching THREE.Geometry?

Is it possible to create a complex object, such as a mountain shape, without using THREE.PlaneGeometry? Can THREE.Geometry be used for this task instead? ...

Implementing Object.somefunction() in ngFor with Angular

In my Angular project, I am using an ngFor loop to iterate over keys generated by Object.keys() in the following code snippet: <ul id='nav-tablist' class='tabrows'> <li *ngFor="let tab of obj.keys(tabList)"> ...