Hi,
I have an array of 3D Objects with different position, How can I create a bounding box with box3 for each object of my array?
I tried this but it doesn’t work
for (let i = 0; i < cubePoz.length; i++) {
const cubeBox = new THREE.Box3().setFromArray(cubePoz[i]);
const helper = new THREE.Box3Helper(cubeBox, 0xff0000);
scene.add(helper);
}
Not sure the method you’re using is possible, likely best to generate a box3 from the original object and clone it for each instance setting them to the same transform as each matrix
You are setting the Box3 from your objects positions, which makes no sense. A single position cannot result in a volume of your mesh. Box3 is a helper class to generate a Boundingbox. Easiest way to set it is to use setFromObject(obj3D). Since you’re using instanceMesh, all objects have the same boundingbox, just at a different location.
let boxes = []
for(let o of objects) {
let box = new THREE.Box3().setFromObject(o)
boxes.push(box)
}
You could also make only one Box3 instance and reuse it
If you still wanna use instancedMesh instead, you can do something like this.
let instancedMesh = new THREE.InstancedMesh(geometry, material, amountOfInstances)
let box = new THREE.Box3().setFromObject(instancedMesh)
// set position of one instance for example
let matrix = new THREE.Matrix4().setPosition(10, 0, 15)
instancedMesh.setMatrixAt(index, matrix)
instancedMesh.instanceMatrix.needsUpdate = true
// Transform the boundingbox to the same position as your mesh instance
box.applyMatrix4(matrix)
// Get center
let center = new THREE.Vector3()
box.getCenter(center)
For each object in your array:
• clone the geometry of InstancedMesh,
• apply to it matrix of certain instance,
• create a new mesh with that geometry
and get the box form it.
for (let i = 0; i < instancedMesh.count; i++) {
const instanceMatrix = new THREE.Matrix4();
instancedMesh.getMatrixAt(i, instanceMatrix);
const geo = instancedMesh.geometry.clone();
geo.applyMatrix(instanceMatrix);
const cubeBox = new THREE.Box3().setFromObject(new THREE.Mesh(geo));
const helper = new THREE.Box3Helper(cubeBox, 0xff0000);
scene.add(helper);
}