Is there a method to extract a bounding box from a Object3D in three.js?

I have successfully loaded an OBJ file with Three.js and OBJLoader.js. The returned object is a Three.Object3D that contains the typical properties of a 3D model (position vector, up vector...)

My current challenge is determining how to obtain a bounding box for this object. Is there a way to achieve this?

Answer №1

Instead of looping through each child of the object, there is a convenient method in the library that handles this task efficiently: THREE.Box3#setFromObject. You can learn more about it by checking out the documentation here. To illustrate, you can utilize the following code snippet:

var boundingBox = new THREE.Box3().setFromObject(targetObject);

This will give you the accurate bounding box of targetObject, taking into consideration all its children as well as any transformations like translations and rotations.

It's important to note that the BoundingBox helper serves the purpose of visually representing a bounding box within the scene, rather than simply calculating the dimensions of an object's bounding box.

Answer №2

To retrieve the precise position and dimensions of the bounding box as it appears within the scene, consider using the BoundingBoxHelper feature:

var helper = new THREE.BoundingBoxHelper(someObject3D, 0xff0000);
helper.update();
// To display a visible bounding box
scene.add(helper);
// To obtain only the numerical values
console.log(helper.box.min);
console.log(helper.box.max);

The use of .boundingBox on the geometry doesn't incorporate any translations, rotations, or scaling applied to the parent mesh, making manual adjustments challenging. However, employing the helper resolves this issue efficiently.

Answer №3

Every shape possesses a boundingBox property within its geometry object. This property contains a THREE.Box3 object, which is made up of two THREE.Vector3 objects, namely min and max.

let geometry = new THREE.CylinderGeometry(...);
let material = new THREE.LineBasicMaterial(...);
let mesh = new THREE.Mesh(geometry, material);

let boundingBox = mesh.geometry.boundingBox.clone();
alert('bounding box coordinates: (' + boundingBox.min.x + ', ' + boundingBox.min.y + ', ' + boundingBox.min.z + '), (' + boundingBox.max.x + ', ' + boundingBox.max.y + ', ' + boundingBox.max.z + ')');

When dealing with more intricate shapes, such as those imported from JSON Object files, the bounding box property is not defined by default. It needs to be explicitly calculated.

let loader = new THREE.ObjectLoader();
loader.load(imagePath, function(object) {

    geometry = object.children[0].children[0].geometry;  // Replace this with the path to your geometry

    geometry.computeBoundingBox();  // Otherwise, geometry.boundingBox will remain undefined

    let boundingBox = geometry.boundingBox.clone();
    alert('bounding box coordinates: (' + boundingBox.min.x + ', ' + boundingBox.min.y + ', ' + boundingBox.min.z + '), (' + boundingBox.max.x + ', ' + boundingBox.max.y + ', ' + boundingBox.max.z + ')');
}

Answer №4

Indeed, you would require a code snippet similar to this:

if (object instanceof THREE.Object3D)
{
    object.traverse (function (mesh)
    {
        if (mesh instanceof THREE.Mesh)
        {
            mesh.geometry.computeBoundingBox ();
            var bBox = mesh.geometry.boundingBox;

            // calculate the composite bounding box
            minX = Math.min (minX, bBox.min.x);
            minY = Math.min (minY, bBox.min.y);
            minZ = Math.min (minZ, bBox.min.z);
            maxX = Math.max (maxX, bBox.max.x);
            maxY = Math.max (maxY, bBox.max.y);
            maxZ = Math.max (maxZ, bBox.max.z);
        }
    });

    var bBox_min = new THREE.Vector3 (minX, minY, minZ);
    var bBox_max = new THREE.Vector3 (maxX, maxY, maxZ);
    var bBox_new = new THREE.Box3 (bBox_min, bBox_max);

    scene.add (object);
}

UPDATE:

This approach dates back to a time before the introduction of BoundingBoxHelper() or BoxHelper()

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

What is the best way to implement a navbar that automatically scrolls the page when a button is clicked?

Let's say I have a navigation button labeled "German", when clicked it smoothly scrolls down to an h2 heading that says "Traditional German Foods". Similarly, if there was a button called "French" in the navbar, the user would be directed further down ...

The length property of a jQuery array may not always match the actual length of the array

Recently delving into jquery, I encountered the issue described in the title. Below is an excerpt from my controller code: [HttpPost] public JsonResult getProjectList() { List<Project> projectList = new List<Project>(); ...

Guide to creating a Discord bot that replies privately to users without other channel members being able to see the messages

As a newcomer to Discord, I am attempting to create a bot that will respond to user commands by sending a reply that only the user who issued the command can see. However, I am struggling to figure out how to implement this feature. Below is the source c ...

Loading jQuery on an ajax request

The loader is working with the code now, but it is not replacing and calling the URL. The ajax url call should be placed within searchable. <button onclick="myFunction()">LOAD</button><br /><br /> <div class="spinner bar hide" ...

Effective Strategies for Preventing Javascript Injection Attacks

My main concern is distinguishing between client-side messages originating from my code and those coming from a potential hacker. Despite researching JavaScript injection and reading various responses on StackOverflow, the consistent advice is to never tru ...

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

Changing the z-index property of a Material-UI <Select> dropdown: What you need to know

Currently, I am implementing an <AppBar> with a significantly high z-index value (using withStyles, it is set to theme.zIndex.modal + 2 which results in 1202). The primary purpose behind this decision is to guarantee that my <Drawer> component ...

The identity becomes blurred once information is transmitted to a modal

I'm having an issue with a recipe table that belongs to a specific user. When the pencil icon on each row is clicked, a modal should display, showing the recipe details and allowing the user to edit and save the updated version. However, I've enc ...

Enhancing array elements with style and class attributes in JavaScript

I am attempting to create a vibrant logo that fades in and out with a random color on hover for each letter in the logo. When I use console.log(word) without any other parameters, I receive an array of "My Portfolio", but it appears that I am unable to app ...

Dealing with invalid JSON in Express: Best Practices

I am looking to handle cases of invalid JSON in my application. For example, if I receive "usern": "James" instead of "username": "James", I want to return a 400 status code. exports.create_user = async (req, res) =& ...

Identifying an Incorrect Function Call in a TypeScript Function from a JavaScript File [TypeScript, Vue.js, JavaScript]

I have a vue2 application and I am looking to incorporate TypeScript into some service files without modifying the existing js/vue files. To enable TypeScript support, I utilized vue-cli which allowed me to successfully add a myService.ts file containing ...

Retrieving information through a jQuery ajax call

I've been working on creating an AJAX filter for a car list, but I've hit a roadblock in the final stage. My setup involves two files: index.php and filter.php. Within index.php, I have a form with dropdown lists and sliders. Here's the cod ...

Is Webpack bundling the node_modules of node_modules into the bundle?

Recently, I noticed that webpack is bundling dependencies from the top-level node_modules directory into my actual bundle. For instance, one of my dependencies, example-dep, relies on lodash and has a nested node_modules directory at node_modules/example-d ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

In Reactjs, it is important that each child in a list is assigned a distinct "key" prop

I am currently working on fetching data in Nextjs/Reactjs after clicking a button, but I am encountering the following error in my console: Each child in a list should have a unique "key" prop Below is my current code where data is displayed wit ...

Why does the value of my input get erased when I add a new child element?

I seem to be facing an issue when I try to add an element inside a div. All the values from my inputs, including selected options, get cleared. Here's a visual representation of the problem: https://i.sstatic.net/UpuPV.gif When I click the "Add Key" ...

Frontend is refusing to remove items from the shopping cart, while the backend is functioning properly in doing so

I've been working on a shopping cart project using Vanilla JS. The interface handles DOM logic, while the backend deals with array manipulation. The issue I'm facing is with a button that's supposed to remove items from the cart. Despite pa ...

How to properly convert JSON into a string within a nested object

Below is the JSON that I am passing and its result when logged in the console: boundary: Array(1) 0: points: Array(98) 0: {x: 117.5, y: 99} 1: Point {x: 116.5, y: 100} 2: Point {x: 116.5, y: 103} 3: Point {x: 114.5, y: 109} 4: Point {x: 113.5, y: 116} 5: P ...

Interacting with three.js using the "requestAnimationFrame" function when clicking

I would like the camera to rotate continuously when pressing the button + = And it seems that there is a trigger for 2 seconds (with a click) and then stops. let btn = document.querySelector('.btn--left'); btn.addEventListener('click',f ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...