Discovering the coordinates of an individual face on a complex geometric shape using Three.js

I have transformed a flat surface into triangles and now I am trying to retrieve the position of each face for animation purposes. However, I seem to be facing some challenges in achieving this.

if (intersects.length > 0) {

    // Check if the closest intersected object is not the same as the previously selected one
    if (intersects[0].object != INTERSECTED) {


        if (INTERSECTED) {
            INTERSECTED.face.color.setHex(INTERSECTED.currentHex);
        }

        INTERSECTED = intersects[0];

        INTERSECTED.currentHex = INTERSECTED.face.color.getHex();
        INTERSECTED.face.color.setHex(0xc0392b);
        INTERSECTED.object.geometry.colorsNeedUpdate = true;

        var position = new THREE.Vector3();
        position.setFromMatrixPosition( INTERSECTED.matrixWorld );
        alert(position.x + ',' + position.y + ',' + position.z);
    }
}

I attempted to use

INTERSECTED.face.matrixWorld.getPosition()
, following guidance from this example, but encountered an error. You can find the complete code in this JSFiddle. Any insights on what might be causing the issue?

Thank you in advance for your assistance!

Answer №1

When working with a THREE.Face3, it's important to note that there are no predefined positions or matrices. Instead, you can utilize the face indexes a, b, and c to determine the associated vertices. From there, you can calculate the centroid of the face (also known as the gravity point) by using these points:

var geometry = INTERSECTED.object.geometry;
var face = INTERSECTED.face;

var vertices = geometry.vertices;
var v1 = vertices[ face.a ];
var v2 = vertices[ face.b ];
var v3 = vertices[ face.c ];

// compute the centroid
var position = new THREE.Vector3();
position.x = ( v1.x + v2.x + v3.x ) / 3;
position.y = ( v1.y + v2.y + v3.y ) / 3;
position.z = ( v1.z + v2.z + v3.z ) / 3;

You can find an updated example in this JSFiddle link.

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 place to define data that remains constant?

In a Vue component, I am looking to utilize data that remains constant. The issue arises when attempting to implement the following code: const numbers = [1, 2, 3] new Vue({ el: "#app" }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2 ...

Using a straightforward approach with v-model in vue.js on an href element instead of a select

Is there a way to utilize an href-link instead of using <select> to switch languages with vue.i18n? <a @click="$i18n.locale = 'en'">EN</a> <a @click="$i18n.locale = 'da'">DA</a> ...

JavaScript can be used to call a web service directly from a content page

Is there a way to call an autocomplete webservice from JavaScript in a content page that is part of the same web app? I have found that when I include a master page, the autocomplete feature stops working. I haven't added a script manager to the maste ...

Tips for augmenting cell with additional data in react-datepicker

Is it possible to include additional text in a cell using react-datepicker? For example, similar to what is shown in this image: view image here ...

Compare the versions of React used in the linked library and the workspace application

As I work on developing a React library containing my commonly used components, I have organized my project structure in the following way: In the root folder, there is my rollup config file and the src/ folder which houses my library. Upon building, the ...

When it comes to utilizing the method ".style.something" in JavaScript

Here is some javascript code that I am working with: function createDiv(id){ var temp = document.createElement('div'); temp.setAttribute("id", id); document.getElementsByTagName('body')[0].appendChild(temp); } c ...

Optimizing 3D rendering efficiency and pipeline for level of detail (LOD) meshes using three.js

Seeking advice after a long time away from working with 3D models, as the landscape has significantly evolved since then. I have highly detailed 3D models (each with over 3 million faces) created from real-world terrain scans that I need to render in a we ...

Surprising discovery of the reserved term 'await'

function retrieveUsers() { setTimeout(() => { displayLoadingMessage(); const response = fetch("https://reqres.in/api/users?page=1"); let userData = (await response.json()).data; storeAllUserDa ...

What is the mechanism by which sending data directly to the response object displays content to the user?

What exactly does the .pipe(res) segment of the code snippet from that article do at the end of the stream? fs.createReadStream(filePath).pipe(brotli()).pipe(res) I have a basic understanding that the first part reads the file and the second compresses i ...

Utilize the body tag to divide elements in ReactJS

Is there a way to assign different body tags to specific components? For example, I want to apply one body tag to the dashboard component and a different one for the sign up page component. ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

Unable to retrieve variable from ajax success function in response

In my MVC view, I have an ajax call that triggers a chain of 5 functions before completion. Each function contains an if/else statement to return its own error message in case of failure, requiring the original page to be reloaded to display the errors. Ho ...

Implementing debounce functionality in Angular using CodeMirror

I've tried various approaches and even referred to This Possible Dup Currently utilizing the ng2-codemirror 1.1.3 library with codemirror 5.33.0 interface Simply attempting to add a DebounceTime operator to the change event of the CodeMirror Editor ...

Updating a data with a JavaScript browser script

Recently, I have been attempting to modify the timer in a game using scripts found on various websites. My coding skills are not top-notch, so I am seeking some assistance. I am keeping my fingers crossed that the timer is not server-sided. Upon inspecting ...

Unable to use the res.send() function

I've been working on a Node.js project. Within the validate.js file, I have defined a class Validate with a static method validateTicket and exported the class at the end. validate.js file const request = require("request"); const config = { urlBas ...

"Glitch in Yahoo Gifshot JavaScript causing issues with frame numbering

I have been using the Yahoo gifshot library to generate gifs from videos. A user uploads a video, and I use this library to dynamically create a gif from that video. However, the issue arises when a user uploads a two-second video but the resulting gif is ...

Reducing Time Series Data: Comparing Average vs Largest-Triangle-Three-Buckets Technique

Currently, I am utilizing Flot Charts to create line charts that display timeseries data. To streamline the visualization process and reduce the number of data points shown, I have implemented a downsampling technique by averaging data points within the s ...

What is the best way to store the JSON data that is returned in a JavaScript function as a variable

My goal is to save the client's IP address in a variable after fetching it in JSON format from api.ipify.org. I have managed to display the IP if I alert the result, but I am struggling to store it in a variable. This code snippet works: <script& ...

Display HTML content generated by JavaScript in the page source

Can the HTML elements I've added through JavaScript and jQuery codes be displayed in the page source (ctrl+U)? ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...