Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the width/height/depth of an Object3D (as if it wasn't rotated)?

I am computing the height of an Object3D like so:

let obj = ... ; // An Object3D instance. Could be a Mesh, Group, etc.
let boundingBox = new THREE.Box3().setFromObject(obj);
let height = Math.abs(boundingBox.min.y - boundingBox.max.y);

When obj is rotated (on the X and/or Z axis), the difference between boundingBox.min.y and boundingBox.max.y increases/decreases, resulting in a height that is different to when it isn't rotated.

But I want to calculate the height of obj as if it wasn't rotated at all. How can I do this?

I'm guessing I need to transform boundingBox's dimensions based on the angle(s) of rotation, but I'm not sure how to do that.


Before rotation:

1

After rotation:

2

(red = obj, blue = boundingBox)

like image 754
XåpplI'-I0llwlg'I - Avatar asked Sep 03 '25 14:09

XåpplI'-I0llwlg'I -


1 Answers

THREE.Box3().setFromObject(obj) will give you the "world-axis-aligned bounding box" of the object. It will explicitly compute the world-coordinates (read: including rotation, position and scale of the object and all of its parents) for all of your vertices.

If you just want the bounding-box of the geometry (without position, rotation, scale of the object), you can just use obj.geometry.boundingBox after calling computeBoundingBox():

obj.geometry.computeBoundingBox(); 
let boundingBox = obj.geometry.boundingBox;

For object-hierarchies, you can do something like this to get an aggregated bounding-box:

function getCombinedBoundingBox(object) {
  const result = new THREE.Box();
  object.traverse(child => {
    // skip everything that doesn't have a geometry
    if (!child.geometry) { return; }

    child.geometry.computeBoundingBox();
    result.union(child.geometry.boundingBox);
  });

  return result;
}

Note that this will only work if the child-objects are not transformed in any way.

like image 114
Martin Schuhfuß Avatar answered Sep 05 '25 03:09

Martin Schuhfuß