Align 3d Objects in a row based on their size

Hi Everyone,

From a loaded .gltf model with several 3d objects in it, I want to create from an array a new object and set them next to each other on the x-axis.

The array would be items = [item_1, item_1, item_2, item_3, item_3, item_1]

Each item has a different width (same height and depth) so basically, it would be:

items[0].x = 0;
items[1].x = items[0].x  + items[0].width;
items[2].x = items[1].x  + items[1].width;

But I can’t seem to find the needed “width” information of each object.

Any help is much appreciated.
Thanks

Hi @Notarmon_Buchli

To get the width information you could use Box3, add the object to box with setFromObject and get the size of the box with getSize()

Something like this:

const boundingBox = new THREE.Box3().setFromObject(object); // object is one of your array items
const size = boundingBox.getSize(new THREE.Vector3( )); // => returns [width, height, deep]

To get all the sizes you should loop trough the array and create a boundingBox for each object and compare the result.

Maybe a good idea its to do that only one time in the initialization and store the size data in a property inside userData so each time you need the size info you can access the data with object.userData.size.

1 Like

Hi @JuanP ,

thank you so much, this helped and it works perfectly.
I tried with a box before but missed the param in the getSize().

I will store the data in the object as suggested, thanks for the input

1 Like