Automatically Positioning and Scaling GLTF Models within Three.js

Whenever I download 3D models from sketchfab.com and bring them into my Three.js scene, they often end up not being centered and appear overly large in size.

I am curious if there is a method to automatically center and adjust the scale of gltf models using a script or software specifically designed for Linux. Alternatively, I would like to know if it's possible to accomplish this directly within Three.js while utilizing OrbitControls to navigate around the object smoothly.

Answer №1

Ah yes, this snippet of code is quite clever. It takes a node as input and calculates its size and center point. Then, it rescales the node so that its maximum extent is 1 and it is centered at coordinates 0,0,0 above the ground on the y-axis.

    let scene = yourScene;
    let boundingBox = new THREE.Box3().setFromObject(scene);
    let centerPoint = boundingBox.getCenter(new THREE.Vector3());
    let objSize = boundingBox.getSize(new THREE.Vector3());

    // Scaling the object to fit into normalized space
    let maxAxisLength = Math.max(objSize.x, objSize.y, objSize.z);
    scene.scale.multiplyScalar(1.0 / maxAxisLength);
    boundingBox.setFromObject(scene);
    boundingBox.getCenter(centerPoint);
    boundingBox.getSize(objSize);

    // Repositioning the object to be centered at 0,halfY,0
    scene.position.copy(centerPoint).multiplyScalar(-1);
    scene.position.y -= (objSize.y * 0.5);

Answer №2

const modelLoader = new THREE.GLTFLoader();
modelLoader.load( 'models/yourmodel.gltf', 
function ( loadedModel ) {
    loadedModel.scene.traverse( function ( obj ) {
        if ( obj.isMesh ) {
            obj.geometry.center(); // adjust center point
        }
    });
    loadedModel.scene.scale.set(10,10,10) // scale the model
    scene.add( loadedModel.scene );
}, (xhr) => xhr, ( error ) => console.error( error ));

To navigate around the object, use controls.target() https://threejs.org/docs/#examples/controls/OrbitControls.target

Answer №3

I adjusted the size in my REACT project using this code snippet!

import React, { useState, useRef, useEffect } from "react";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
const Planet = () => {
  const [model, setModel] = useState();
  useEffect(() => {
    new GLTFLoader().load("scene.gltf", (model) => {
      model.scene.scale.set(0.03, 0.03, 0.03);
      setModel(model);
    });
  });
  return model ? <primitive object={model.scene} /> : null;
};

To implement the resized model, simply insert <Planet />

Answer №4

I didn't have much luck with the other solutions that were suggested to me. However, I decided to try out a different method on various models that needed to be loaded into my scenes, and it turned out to work really well.

const loader = new GLTFLoader();
loader.load("assets/model_path/scene.gltf",
      (gltf) => {
        gltf.scene.scale.multiplyScalar(1 / 100); // adjust scalar factor to match your scene scale
        gltf.scene.position.x = 20; // once rescaled, position the model where needed
        gltf.scene.position.z = -20;

        scene.add(gltf.scene);
        render();
      },
      (err) => {
        console.error(err);
      }
    );

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

Relocate the resizable handles in jQuery outside of the div elements

I currently have 3 nested divs. Using jQuery $(function() { $("#div1").resizable({ handles: "n, e, s, w, nw, ne, sw,se" }); $("#div1").draggable(); }); Within the HTML structure <div id="div1" style="left: ...

Tips for executing shallow array duplication in mobx

In my code, I have been utilizing the lodash function _.CloneDeep to copy an object array. However, I actually need a shallow copy of this array. Here's the relevant code snippet: @observable.ref trades: Array<TradeType> = []; @action attachN ...

Arranging an array in alphabetical order, with some special cases taken into consideration

Below is a breakdown of the array structure: [{ name: "Mobile Uploads" }, { name: "Profile Pictures" }, { name: "Reports" }, { name: "Instagram Photos" }, { name: "Facebook" }, { name: "My Account" }, { name: "Twi ...

Explain how the 'next' function works within Express middleware and its role in directing the flow to a different function

I am fairly new to Node.js and currently learning Express.js. I am focusing on implementing "middleware functions" for specific routes. My question is regarding the usage of the "next" function. What exactly can we do after authentication using the "next ...

Is there a reason why Express is unable to serve static files?

I'm facing an issue with linking my Express app's static files to update its frontend. Here is the structure of my files: - app -- api --- routes.js -- node_modules -- public --- img --- css ---- styles.css --- index.html -- app.js -- package-loc ...

The color of the background does not remain changed permanently

I'm having an issue where the background color changes when I click a button, but reverts back almost immediately to its original color. How can I ensure that the new color stays permanently? Here is a simple JavaScript function you can use: functio ...

npm is consolidating all dependencies and their sub-dependencies into a single unified directory

My project has a package.json file with approximately 20 dependencies. Upon running npm install, all the dependencies and sub-dependencies end up in the main node_modules directory, resulting in hundreds of modules rather than just my intended 20. The sub- ...

Implement a feature that adds a circle element when an image is clicked in a React application

I am attempting to create a program that allows users to add circles to an image by clicking on it. Essentially, when the user clicks at coordinates (x,y), a circle with a radius of 10 will appear at that location. I am exploring ways to implement meta-pro ...

Unable to trigger window.open function or it is not being invoked

I am facing an issue with a button on my form that generates PDF files and saves them to the local machine. I want to be able to not only save the files locally but also have them available for download in the browser, especially when there are multiple fi ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

What is the process for modifying the headers of a post request in Express when

I have a Node/Express application and I'm looking to incorporate an image upload feature into an order form. While I can successfully use the action link in the HTML form to perform a POST request, I also want my JavaScript file associated with this ...

Calculate the total value of each individual subject from the checkbox's data-id, presented in a string format and separated by commas

<div> <input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science, Physical Education, Agriculture, Yoga, "> <label class="custom-control-label" for="Q_1_ck1"> ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Installation of 'aerogear-cordova-push' was unsuccessful due to an undefined error

When I run sudo ionic platform add ios, I encounter the following error. I added the 'aerogear-cordova-push' plugin, then removed the platforms and attempted to add them again. Failed to install 'aerogear-cordova-push':undefined Error ...

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

Substitute the information in the table with new data

I am working with an HTML table that has 5 columns, one of which contains dates. I need to convert the date format only if the data is not empty. To achieve this, I am utilizing moment.js for date formatting. While the date format conversion works perfect ...

Navigating Three.js coordinate systems

While working with vectors in three.js, I noticed that the axes seem to be mixed up. It's confusing because Y is the vertical axis, but X and Z appear "mirrored" causing objects to only look right when viewed upside-down. How can this issue be resolv ...

Using ajax and node.js for a RESTful login function

I'm currently facing an issue with implementing a basic login functionality on a server and verifying the login status by sending a GET request to retrieve the user name. My setup includes a node.js server and a single page object utilizing JQuery. / ...

According to npm, the JSON is not valid, but jsonlint.com confirms that it is valid

Here is the json file for package.json that I used npm install on (specifically for the angularfire-seed project on github): { "name": "angularfire-seed", "description": "A starter project for Angular + Firebase with AngularFire", "version": "1.0.0 ...

Visualizing JSON data in React.js using Chart.js

Currently, as a beginner in ReactJS, I am working on an application that displays COVID-19 data from a JSON API in a visual format using Chart.js. However, despite trying various solutions, I am unable to visualize the data. Below is my source code: App ...