Adjust 3D Model in ThreeJS to Fit Bounding Box Dimensions

I need to adjust the scale of the imported GLB Model to match the size of a cube in my scene. This is necessary to ensure that the model remains within the shadow casting areas and is large enough to display the shadows effectively.

I have already determined the bounding boxes of both objects:

// shadowcasting area 
var sceneExtent = new THREE.BoxGeometry( 4, 4, 4 );
var cube = new THREE.Mesh( sceneExtent, material );
var sceneBounds = sceneExtent.computeBoundingBox()

and

// imported mesh
model.traverse( function ( child ) {
    if ( child.isMesh ) {
        child.geometry.computeBoundingBox()
        meshBounds = child.geometry.boundingBox
    }
} );

However, I am unsure of how to use this information to adjust the scale of the GLTF Model

// meshBounds = child.geometry.boundingBox
// sceneBounds = sceneExtent.computeBoundingBox()

// how to resize model scale to match size of sceneBounds

model.scale.set(1,1,1)

I have tried researching solutions, but I am struggling to find a clear answer.

Is there a way for me to adjust the model scale to match the sceneBounds based on the provided information?

UPDATE: Use .setFromObject() to obtain the bounding box:

sceneBounds = new THREE.Box3().setFromObject( cube );
meshBounds = new THREE.Box3().setFromObject( model );

Answer №1

For instance, consider the following:

// Calculate the lengths of the bounding box of the scene (cube)
let sceneBoundLength = {
  x: Math.abs(sceneBounds.max.x - sceneBounds.min.x),
  y: Math.abs(sceneBounds.max.y - sceneBounds.min.y),
  z: Math.abs(sceneBounds.max.z - sceneBounds.min.z),
};

// Calculate the lengths of the bounding box of the glb-model
let modelBoundLength = {
  x: Math.abs(meshBounds.max.x - meshBounds.min.x),
  y: Math.abs(meshBounds.max.y - meshBounds.min.y),
  z: Math.abs(meshBounds.max.z - meshBounds.min.z),
};

// Calculate the length ratios
let ratios = [
  (sceneBoundLength.x / modelBoundLength.x),
  (sceneBoundLength.y / modelBoundLength.y),
  (sceneBoundLength.z / modelBoundLength.z),
];

// Find the smallest ratio to fit the model within the scene
let smallestRatio = Math.min(...ratios);

// Optional padding around the model
let padding = 0;
smallestRatio -= padding;

// Scale the model using the smallest ratio
model.scale.set(smallestRatio, smallestRatio, smallestRatio);

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

How to Fetch Byte Image with Ajax and Display it on the Client Side in ASP.Net MVC

After converting an image to bytes, I am facing the challenge of displaying the byteImage in a browser. I have two sets of data, one being the Image ID and the other being the Image_name, which are displayed in a table. However, I am unable to display the ...

Having trouble locating an external Javascript file in a Node.JS/Express app with Jade template?

In my Node.JS/Express app, I am using the Jade template engine. The issue arises when trying to reference a server-side Javascript file named common_routines. Despite placing the Javascript file in the directory above my views directory and referencing it ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

The swipe function of Hammer.js is unable to detect gestures on a rotated iframe

After creating a rotated iframe on the page using CSS transforms, I attempted to implement swipe events within the iframe. body.rotate iframe { transform: rotate(90deg); transform-origin: top right; position: absolute; t ...

``The background color will dynamically change according to the result of a function

My function named shift_color generates different color codes like "#FF5F74", "#5FFF66", and "#5F8AFF". I am looking to use this output to style a navigation menu background. I have tried the following code: .topnav { background-color: <?php echo shi ...

Customizing the appearance and dimensions of JWPlayer Audio Player with percentage-based styling

I'm currently attempting to set up an audio embed using JWPlayer, following the instructions provided in this particular article. The article suggests setting it up with the following code: <div id="myElement">Loading the player...</div> ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...

What is the process for obtaining a compilation of JavaScript files that are run when an event is triggered?

How can I generate a list of all the JavaScript files that are triggered when a button is clicked or an input field is selected in a complex system? Is it possible to achieve this with Chrome DevTools, or are there alternative solutions available? If Chro ...

Upon triggering a GET request to the URL "http://localhost:3000/search", a "404 (Not Found)" error response was received. Interestingly

Can Someone assist me please? I'm having trouble creating a website similar to YouTube and encountering the following error: GET http://localhost:3000/search 404 (Not Found) Uncaught (in promise) Error: Request failed with status code 404 at createEr ...

What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciat ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Issue with Ajax form submission - unable to retrieve POST data in PHP

My goal is to utilize Ajax for form submission. Upon clicking the button, the hit() function will be triggered and send the data from the textbox back to test.php The issue arises with $_POST being empty as indicated by the alert message from Ajax (form w ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...

Ensuring that each object in a list contains an optional key if any one object includes it is a task handled by Joi validation

My dataset includes various objects that must have certain keys: Date, Time, Price I am looking to include an optional key "order" for these objects. If one of them has the "order" key, then they all should. Is there a way to validate this using joi? ...

Deleting an ID from an array within a document using Node.js Mongoose

In my model document, there is an array that I am working with. I want to be able to remove a specific ID from this array. Is it possible to do so? https://i.sstatic.net/agaD3.png Below is what I attempted. module.exports.RemoveFavourite = async (req, re ...

Utilizing null values within the map function in React JS

I am currently developing an application using React JS. The app displays a list of users along with the status of books (available, taken, or requested) for each user. However, I'm encountering an issue where even after filtering out the books based ...

How can I accurately determine the true dimensions of an image in Angular, including any resizing that may

Here is an image: @ViewChild('image') readonly photo: ElementRef; The HTML code for the image is: <img #photo class="pic" /> How can I find the original size (width, height) as well as the resized dimensions after applying CSS a ...

Tips for properly aligning an image within an owl carousel

Currently, I am attempting to center a small image within the owl carousel. While I have managed to center it when it's active and in the center, I'm encountering issues when the item no longer carries the "center" class. You can access Owlcarou ...

React event handling

Currently, I am in the process of developing an accordion app using React. The data for this app is fetched from an API, and while I have the basic structure of the app ready, I am facing some difficulties with handling the click event on the accordion. H ...