Position the model in the center of the scene using three.js

Currently, I am utilizing the code below to center an object within the scene. While it works perfectly with the json loader, the issue arises when using either OBJLoader or OBJMTLLoader.

function modelLoadedCallback(geometry, materials) {

    // Create the object based on the loaded geometry and materials, allowing for multiple materials via MeshFaceMaterials.
    // Please note that materials may contain references to texture images that could finish loading later.

    var object = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));

    // Determine the range of x, y, and z values in the geometry vertices.

    var xmin = Infinity;
    var xmax = -Infinity;
    var ymin = Infinity;
    var ymax = -Infinity;
    var zmin = Infinity;
    var zmax = -Infinity;
    for (var i = 0; i < geometry.vertices.length; i++) {
        var v = geometry.vertices[i];
        if (v.x < xmin)
            xmin = v.x;
        else if (v.x > xmax)
            xmax = v.x;
        if (v.y < ymin)
            ymin = v.y;
        else if (v.y > ymax)
            ymax = v.y;
        if (v.z < zmin)
            zmin = v.z;
        else if (v.z > zmax)
            zmax = v.z;
    }

    // Translate the center of the object to the origin.
    var centerX = (xmin + xmax) / 2;
    var centerY = (ymin + ymax) / 2; 
    var centerZ = (zmin + zmax) / 2;
    var max = Math.max(centerX - xmin, xmax - centerX);
    max = Math.max(max, Math.max(centerY - ymin, ymax - centerY));
    max = Math.max(max, Math.max(centerZ - zmin, zmax - centerZ));
    var scale = 10 / max;
    object.position.set(-centerX, -centerY, -centerZ);
    console.log("Loading finished, scaling object by " + scale);
    console.log("Center at ( " + centerX + ", " + centerY + ", " + centerZ + " )");

    // Create a wrapper, model, to scale and rotate the object.
    model = new THREE.Object3D();
    model.add(object);
    model.scale.set(scale, scale, scale);
    rotateX = rotateY = 0;
    scene.add(model);
    render();

}

This is causing a TypeError: s is undefined, preventing my model from displaying on the scene. What could be the issue here? Are there any alternate methods available to center the object using OBJLoader or OBJMTLLoader?

Answer №1

To determine the center of your model, there's no need to go through each vertex individually. Utilize the geometry.computeBoundingBox() method to calculate the bounding box of your geometry. Visit for more details.

If you have a Geometry node, you can simply execute the following:

geometry.computeBoundingBox();
var bBox = geometry.boundingBox;
alert('Bounding box coordinates: ' + 
    '(' + bBox.min.x + ', ' + bBox.min.y + ', ' + bBox.min.z + '), ' + 
    '(' + bBox.max.x + ', ' + bBox.max.y + ', ' + bBox.max.z + ')');

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

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

I'm having trouble getting a http.request to run within an imported module. It just doesn't seem to work when I try to access

Here is the code from my main.js file: var spaceJson = require('./space.js'); var options = { "method": "GET", "hostname": "10.10.111.226", "port": null, "path": "/API/Org", "headers": { "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJ ...

The render of Javascript is not functioning properly in Chromedriver

For website testing in VisualStudio, I planned to use Selenium with Cromedrive. Unfortunately, I encountered difficulty in seeing items generated by Javascript on the page. It appears that chromedriver captures the pagesource before the JS has a chance to ...

Build a nested block containing a div, link, and image using jQuery or vanilla JavaScript

I have a button that, when clicked, generates a panel with 4 divs, multiple href links, and multiple images. I am new to web programming and understand that this functionality needs to be in the Javascript section, especially since it involves using jsPlum ...

Having trouble with the dropdown multiselect feature in AngularJS?

I'm striving to develop a straightforward multi-select dropdown utilizing angular JS, bootstrap, and JS. This dropdown should display days (mon, tue...sun), with options for select all and unselect all. My goal is to create a controller that will de- ...

Tips for eliminating flutter for static menu with easyResponsiveTabs.js

Experiencing a flickering issue with the fixed menubar and easyResponsiveTabs.js in my project when scrolling down. Attempted to resolve it using jquery.noConflict(), but without success. Would appreciate any guidance on how to address this problem. ...

What is the most effective method for fetching images from MongoDB?

I'm currently working on a web application that uses MongoDB's GridFS to store and retrieve images. However, I'm facing an issue where retrieving images from the database takes significantly longer than expected when a user makes a request. ...

What could be the reason for the inability to install Angular JS 2?

Setting up Angular 2 for experimentation on my VPS has been quite a challenge. The initial steps can be found here. Upon trying the first command: $ npm install -g tsd@^0.6.0 I encountered success. However, the second step led to an error: tsd install ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

Can someone guide me on implementing Node.js clusters in my basic Express application?

— I have successfully developed a basic application that retrieves data (50 items) from a Redis DB and displays it on localhost. After running an ApacheBench test with parameters c = 100, n = 50000, I am achieving around 150 requests/sec on my aging dual ...

What is the preferred default value for a property awaiting assignment from a GET response: Undefined or Null?

Say I need to display information about a product, but first I must make a GET request to get the data and assign it to the product. I'm wondering, should the default value for product in the data() function be undefined or null, and is there a differ ...

- increase clarity and readability- separate sections for better

I'm working on a code snippet to showcase 4 buttons: #buttons { text-align: center; padding-top: 4%; } #buttons img { display: inline-block; list-style: none; padding: 10px; } #buttons p { color: #fff; font-family: ; font-weight: ...

Leveraging the power of jQuery Validation in conjunction with Bootbox

I am currently facing an issue with integrating the jQuery validation plugin with bootbox.js (modals). The modal contains a form with fields that require validation. To showcase my problem, I have set up a jsFiddle here: http://jsfiddle.net/rDE2q/ Upon ...

Using Javascript to Retrieve Icecast Metadata

I am currently developing a web radio application that utilizes AngularJS and Laravel 5 to read Icecast streams. Currently, I have implemented loading the stream into an html5 audio element which is working well. However, I am facing an issue where the vie ...

Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a parti ...

Why does the <div> element still have an offset even though its width and height are set to 100px and padding, margin, and border are set to 0px?

After styling my div element with specific CSS rules, I'm encountering an issue. The div has a set width and height of 100px along with padding, border, and margin all set to 0px. However, the elements are not being offset from the edges of the browse ...

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...