How can I retrieve the precise location of a loaded .obj file in three.js?

When trying to load the .obj file:

        loader.load( 'test.obj', function ( objMesh ) {
                objMesh.traverse( function ( child ) {
                if ( child instanceof THREE.Mesh ) {
                       child.material = mat2;
                }
            } );

I attempted to determine the position using mrdoobs code:

objMesh.geometry.computeBoundingBox();

var boundingBox = objMesh.geometry.boundingBox;

var position = new THREE.Vector3();
position.subVectors( boundingBox.max, boundingBox.min );
position.multiplyScalar( 0.5 );
position.add( boundingBox.min );

position.applyMatrix4( objMesh.matrixWorld );

alert(position.x + ',' + position.y + ',' + position.z);

However, I encountered the following error:

objMesh.geometry is undefined

Does this mean it is not possible with loaded meshes?

Answer №1

It might be possible, however, based on your situation it appears that the objMesh variable is local within the scope of the function ( objMesh ) {...}.

You could create a global variable, let's name it mesh, and then assign its value within the onLoad callback function:

var mesh;
...
loader.load( 'example.obj', function ( objMesh ) {
    objMesh.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.material = material2;
            mesh = child; // assigning the value to the global variable, this is applicable if objMesh has a single child of THREE.Mesh()
        }
    });

After that, you can utilize mrdoob's code on the mesh variable instead of objMesh.

Alternatively, you can encapsulate mrdoob's code within a function and then invoke this function in the onLoad callback function with your mesh as a parameter:

function absolutePosition( myMesh ){
    myMesh.geometry.computeBoundingBox();

    var boundingBox = myMesh.geometry.boundingBox;

    var position = new THREE.Vector3();
    position.subVectors( boundingBox.max, boundingBox.min );
    position.multiplyScalar( 0.5 );
    position.add( boundingBox.min );

    position.applyMatrix4( myMesh.matrixWorld );

    alert(position.x + ',' + position.y + ',' + position.z);
}

Call it within the callback function:

loader.load( 'example.obj', function ( objMesh ) {
    objMesh.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.material = material2;
            absolutePosition( child ); // invoking our function
        }
    });

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 there a way for me to delay sending an immediate response until the asynchronous loop has completed?

Currently trying to implement something similar to the code snippet below. I suspect that the issue lies within the asynchronous call as it seems like the response I am getting is always an empty array, despite the API returning data. As a beginner in th ...

What is the reason behind the enhancement in rendering speed when merging geometries?

While working on my web application, I encountered a speed issue when adding static objects to my scene. After some research, I discovered that merging geometries and vertices could solve the problem. When I implemented this solution, the performance impro ...

Pause and wait for the completion of the Ajax call within the function before assigning the object to an external variable

In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel0 ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

TypeAhead.js and Bloodhound displaying an uneven quantity of search outcomes

I have a frontend setup with TypeAhead and Bloodhound integration, fetching JSON data from a Play/Scala server. The version of Typeahead being used is 0.11.1. Here is how the implementation looks: HTML: <div id="typeahead" class="col-md-8"> < ...

What is the best way to add a blob to the document object model (

I am a beginner when it comes to working with blobs, and I am looking for some guidance to avoid wasting hours on unsuccessful brute-force attempts. I have been using the PHP code below (sourced from here) to retrieve the base64-encoded image from my data ...

Exploring the power of Vuejs3 with Internationalization and the Composition API

Currently, I am working on a frontend interface in VueJS and integrating i18n with Vuejs 3. While the normal implementation of i18n works fine, I encountered issues when trying to use it with the composition API. In my main.js file, I have set up i18n as ...

Issues with the styling of C3.js

I'm encountering some issues with a visualization I'm trying to create using C3.js. The top and side edges of my scatter chart are getting cropped (likely due to changing the radius of the bubbles), but I don't believe that should be cau ...

Is it necessary for me to use a .jsx extension when saving my React component files?

After working with React for a few months, I recently noticed that some of my files have the .js extension while others have the .jsx extension. Surprisingly, when I write JSX code in the .js files, everything still functions correctly. Is there any signif ...

Generating elevation graph from a kml file with the combination of php and javascript

Currently, I am exploring the Google Elevation Service with the goal of creating an elevation profile similar to the one showcased in this example: Below is the JavaScript code snippet used: var elevator; var map; var chart; var infowindow = new google.m ...

Ways to dynamically combine a group of objects

I'm grappling with a challenge involving an array containing two objects. After using Promise All to fetch both of these objects, I've hit a roadblock in trying to merge them dynamically. Despite experimenting with various array methods like map, ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

Displaying a random item from the state in React.JS

After storing some items in the state, I want to have the ability to click a button and have a random item from that array displayed. The current issue is that it only works on the initial click, and then it continually displays the same item after the fir ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

selenium.common.exceptions.WebDriverException: Message: IndexError: array index out of bounds

I've been working on creating a web scraping tool that involves a Python script and a JavaScript code. The Python script is designed to call the JavaScript code, which then extracts relevant content from a web page and sends it back to the Python scri ...

moment.js conversions proving ineffective

My input field requires users to select a date and time. The local machine is either in GMT or BST depending on the time of year. For those unfamiliar with UK time changes: GMT (Greenwich Mean Time) is always equal to UTC BST (British Summer Time) is GM ...

Is the server delivering an unexpected response?

Implementing a post request using the fetch API in React JS, I provide a URL to the server from the frontend. The server then utilizes this URL to make an API call to Clarifai API. The expected response is received from the API; however, when transferring ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...

Simple guide to returning values from PHP using AJAX

I have a script on my login page that uses AJAX to send data to PHP, and PHP then returns whether the login was successful or not. I am curious about how I can modify my scripts to also send back two variables and receive them in my login JavaScript so tha ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...