I am struggling to center external objects loaded into my scene. ANY help will be much appreciated as I am truly stuck.
I create complex mesh objects myself that work perfectly in my project. I center these objects without issue.
My issue is only with objects imported via OBJLoader and GLTFLoader.
I created the code snippet below for troubleshooting. Note that this.mesh is the imported mesh object, which has been added to this.root which is an object3D object already added to the scene.
bbox = new THREE.Box3().setFromObject(this.root);
let center = bbox.getCenter(new THREE.Vector3());
size = bbox.getSize(new THREE.Vector3());
console.log("Root position before centering: ",this.root.position);
console.log("Mesh position relative to root before centering: ", this.mesh.position);
console.log("Boundary box before centering: ", bbox)
console.log("Size of object: ", size)
console.log("Calculated center:", center);
this.mesh.position.x = this.root.position.x - center.x;
this.mesh.position.y = this.root.position.y - center.y;
this.mesh.position.z = this.root.position.z - center.z;
console.log("Root position after centering: ",this.root.position);
console.log("Mesh position relative to root after centering: ", this.mesh.position);
bbox = new THREE.Box3().setFromObject(this.root);
center = bbox.getCenter(new THREE.Vector3());
size = bbox.getSize(new THREE.Vector3());
console.log("New boundary box after centering: ", bbox)
console.log("New size of object: ", size)
console.log("New calculated center:", center);
Here is the cleaned up result from the console window:
Root position before centering: { x: 0, y: 0.1, z: 2.5 }
Mesh position relative to root before centering: { x: 0, y: 0, z: 0 }
Boundary box before centering:
max: { x: 0.1025499, y: 0.590832, z: 2.6086639 }
min: { x: -0.1078011, y: 0.090832, z: 2.4120308 }
Size of object:{ x: 0.210351, y: 0.5, z: 0.1966330 }
Calculated center: { x: -0.00262559, y: 0.3408326, z: 2.510347 }
Root position after centering: { x: 0, y: 0.1, z: 2.5, … }
Mesh position relative to root after centering: { x: 0.00262559, y: -0.2408326, z: -0.0103473 }
New boundary box after centering:
max: { x: 0.10281247, y: 0.566749352, z: 2.6076291 }
min: { x: -0.10753854, y: 0.066749352, z: 2.41099611 }
New size of object:{ x: 0.210351, y: 0.5, z: 0.1966330 }
New calculated center: { x: -0.002363, y: 0.3167493, z: 2.5093126 }
What I expected to see was the “New calculated center” to be equal to the “Root position”. Can anyone clarify what I am missing?