Issue with obtaining centroids of geometries in Three.js r68 when using OBJMTLLoader

After sticking with an outdated version of Three.js for a while, I decided to upgrade to the latest (r68). Little did I know, I would encounter some unexpected issues - specifically, the removal of geometry.computeCentroids() and .centroid property.

My current challenge lies in loading models using the OBJMTLLoader library. The absence of the .computeCentroids() method means I am unable to retrieve them. Despite my attempts to calculate centroids through alternative methods, such as:

  • Three.js How to get position of a mesh?
  • Three.js move and rotate the center of geometry
  • Three.js Child Mesh position always return (0,0,0)

Even attempts at using the .localToWorld(point) methods have proven futile, consistently returning (0,0,0).

In my current workaround, when I click on a mesh, I apply the following calculation:

 if (mesh.centroid === undefined) {
    mesh.centroid = new THREE.Vector3();
    mesh.centroid = mesh.geometry.center();
    console.log(mesh.centroid); }

A similar approach is taken when adding a new object to the scene:

//desperate try to find different values for centroids
object.updateMatrix();
scene.updateMatrix();
object.updateMatrixWorld();
scene.updateMatrixWorld();

Strangely enough, the calculated centroids are not consistent. Regardless of the mesh clicked or the order, the console.log() displays the same vectors every time:

THREE.Vector3 {x: 158.89799999999997, y: -4.115949999999998, z: 67.75310000000002, constructor: function, set: function…}
THREE.Vector3 {x: 0.000005004882780212938, y: 0.16375010757446518, z: 0.0000024658203301441972, constructor: function, set: function…}
THREE.Vector3 {x: -1.7053025658242404e-13, y: -0.0818749484539012, z: 1.1368683772161603e-13, constructor: function, set: function…}

If anyone has encountered a similar issue, please share your experience. Though I haven't explored previous versions of three.js, my goal is to stick with the latest update.

Your insights are greatly appreciated.

EDIT: An important detail I failed to mention earlier - the desired centroid should be in WORLD coordinates.

Following mrdoob's suggestion, I managed to obtain centroids. However, the identical values across meshes suggest that .calculateBoundingBoxes() calculates based on the main parent object, rather than individual geometries. Each geometry contains all vertices of the object, leading to the uniform bounding box values.

Answer №1

To find the centroid of the entire geometry, you can use the following code snippet:

geometry.calculateBoundingBox();

var centerPoint = new THREE.Vector3();
centerPoint.addVectors( geometry.boundingBox.min, geometry.boundingBox.max );
centerPoint.multiplyScalar( - 0.5 );

centerPoint.applyMatrix4( mesh.matrixWorld );

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

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

Integrate these scripts for seamless functionality: JavaScript/AJAX and PHP

Currently, I am in the process of learning all the languages involved here and facing a challenge while trying to merge two scripts to perform a single task. The goal is to select a branch from a form option list, transmit that value from the option to a ...

Having trouble getting the items to show up on the canvas

I have been struggling to implement JavaScript on a canvas in order to display mice in the holes using the mouse coordinates. Despite trying many different methods and spending close to a month on this project, I still can't seem to get it to work acr ...

Combine two JSON objects which share a common attribute

I am currently working with two JSON feeds. One feed contains the basic information about a course, while the other contains more administrative details. Here is an example to illustrate what I mean. FIRST {"courses": {"course":{"id":"4","title":"Usi ...

The issue of an unsuccessful Ajax call arises in a WordPress plugin when utilizing wp_remote_get

Encountering difficulties with the wp_remote_get function in my Wordpress plugin. The objective is to invoke a method within my primary public class using ajax. However, every time I attempt to make the call with the wp_remote_get function, it fails. This ...

PugJS is failing to properly interpolate numbers from the JSON file

My goal is to display a list of interfaces retrieved from my router API, which is in JSON format. However, when using Pug, only the strings are being rendered and not the numbers. Here is the output (it displays correctly in HTML): em1 192.168.0.0/24 Addr ...

There is an error in ReactJS: TypeError - _this.props.match is not defined

I am experiencing a TypeError in my console tab and I can't seem to figure out where the error is occurring in my source code. I am relatively new to ReactJS so any help in identifying what I'm doing wrong would be greatly appreciated. Thank you ...

What strategies can be employed to tackle the challenges posed by Ajax asynchronous calls?

Beginner in JavaScript - I just wanted to mention that upfront. Take a look at this straightforward example where I aim to create X number of gauges, with the value of X being retrieved from JSON using an Ajax call. <body> <div id="gServer"> ...

JavaScript failing to link an element to the object

const modifyTimestamp = async (request, response) => { try { const { user: userid } = request; if (!ObjectId.isValid(userid)) throw new Error('invalid objectid'); const now = moment().format(); const date = new Date(now); ...

"Experience the power of Vue.js 3 and vue-router as the @click event seamlessly refreshes the entire

Just getting started with Vue and I'm trying to figure out how to toggle the menu open/close on mobile navigation without causing the whole page to reload. Any suggestions on how to prevent that? Here's my code: <router-link to="/ " @click="t ...

Utilizing crossfilter and DC.js to perform reduce() on groupAll() operation

This task seems deceptively simple :/ I've been following the crossfilter API instructions on running a reduce operation on groupAll: https://github.com/square/crossfilter/wiki/API-Reference#groupAll_reduce However, despite my efforts, I can't ...

Adjust the appearance of elements depending on whether the user has activated dark mode or

What is the most efficient way to implement both dark and light themes in my Vue app? One option is to create a 'dark.scss' file and use the '!important' property to override styles defined in components. Another option is to utilize pr ...

Displaying data from asynchronous functions in Vue.js

As a beginner in VueJs, my goal is to develop a basic application that fetches text from a Wikipedia page and displays it upon clicking a button. Code <script> const wiki = require('wikipedia'); export default { data() { sum:&q ...

Removing an object from a JSON array based on checkbox selection in Angular 4

0: CategoryId: "31b7a227-9fda-4d14-8e1f-1dee5beeccb4" Code: "GMA0300" Description: "PA-5215: Renamed" Enabled: true Favorite: false Id: "26cfdb68-ef69-4df0-b4dc-5b9c6501b0dd" InstrumentType: null Moniker: "1GMA0300" Name: "Celiac Disease Panel (tTG IgG, tT ...

Access cookie information within a Vue application by reading it within the router or component

There is a url (*/webapp/callback) in my vue.js app that gets redirected (http 302) from another application, bringing along some cookies. I'm trying to figure out how I can read these cookies when the component mounts and then store them in vuex stat ...

What causes the output of Math.pow(a, b) to be NaN when the value of a is negative and b is not a whole number?

After observing different JavaScript behaviors, I noticed the following: > Math.pow(4, 2) 16 > Math.pow(4, 2.1) 18.37917367995256 > Math.pow(4, 0.5) 2 > Math.pow(-4, 2) 16 > Math.pow(-4, 2.1) NaN > Math.pow(-4, 0.5) NaN Why does using a ...

Issue encountered while requesting data from API in ReactJS

I've been trying to fetch data from using the react useEffect hook. However, instead of displaying the data, I keep getting an error message that says, "Error: Objects are not valid as a React child (found: object with keys {number, name}). If you me ...

What is the maximum number of requests that Node-Express can send simultaneously?

Currently, I am facing a challenge with my script that involves fetching 25,000 records from AWS Athena, a PrestoDB Relational SQL Database. For each of these records, I need to make a request to Athena and then another request to my Redis Cluster once the ...

Tips for properly formatting the data before sending it to an API

When a user submits a form, the data is sent to an API. It's important that every field appears on a new row in the output. Unfortunately, using \n and <br> inside the string does not produce the desired formatting. Can you help me with thi ...

Having trouble loading this JSON data into my table

So I have a little challenge on my hands: I've got a JSON file with information about various books, each including details like title, author, and year of publication. The goal is to select an option from the list and display the chosen property in ...