I am trying to create a simple bounding box around my 3D objects for collision detection. Models are .glb loaded files. Each model is composed of multiple Meshes.
When using boxHelper on my Object3D directly, the bounding box is not accurate:
Here is my code:
MyScene.traverse((child) => {
if (child instanceof THREE.Object3D && child.name.includes("UZI")) {
var boxHelper = new THREE.BoxHelper( child );
this.scene.add( boxHelper );
Is this the expected behaviour?
Note that objects I am trying to create a bounding box for are little uzi guns.
So I came up with a workaround:
MyScene.traverse((child) => {
if (child instanceof THREE.Object3D && child.name.includes("UZI")) {
const boundingBox = new THREE.Box3();
child.traverse((subChild) => {
if (subChild instanceof THREE.Mesh) {
const meshBoundingBox = new THREE.Box3().setFromObject(subChild);
boundingBox.union(meshBoundingBox);
}
});
createBoundingBoxMesh(boundingBox, child);
function createBoundingBoxMesh(boundingBox, object) {
// Calculate the size of the bounding box
const size = boundingBox.getSize(new THREE.Vector3());
// Calculate the center of the bounding box
const center = boundingBox.getCenter(new THREE.Vector3());
// Create a box geometry using the size of the bounding box
const boxGeometry = new THREE.BoxGeometry(size.x, size.y, size.z);
const randomColor = new THREE.Color(Math.random() * 0xffffff);
// Create a wireframe material to visualize the bounding box
const boxMaterial = new THREE.MeshBasicMaterial({ color: randomColor, wireframe: true });
// Create a box mesh using the geometry and material
const boxMesh = new THREE.Mesh(boxGeometry, boxMaterial);
// Set the position of the box mesh to the center of the bounding box
boxMesh.position.copy(center);
object.add(boxMesh);
}
Here is the result:
It feels like a lot of work just to create a bounding box around an object…
Is this the right approach to create bounding boxes for collision detection (using Ammo.js) ?
Thanks