I am trying to figure out how to load an OBJ file and translate its coordinates to the world origin (0,0,0) in order to make orbit controls function smoothly without using Pivot points.
My goal is to automatically translate random OBJ objects with different geometries/center points to the scene origin. I need a flexible solution that can work for any model, not just a hardcoded translate for a specific one.
This seems like a common scenario in Three JS (basic 3D object viewer), but surprisingly I haven't been able to find a definitive solution on Stack Overflow.
Many of the older answers I've come across use deprecated functions, so I'm hoping for a fresh answer even if there are similar solutions already available.
Some things I've experimented with:
The code snippet below helps fit the object nicely within the camera view, but it doesn't completely solve the translation/orbiting issue.
// Fit camera to object var bBox = new THREE.Box3().setFromObject(scene); var height = bBox.size().y; var dist = height / (2 * Math.tan(camera.fov * Math.PI / 360)); var pos = scene.position; // Adjust position so object isn't too close or far camera.position.set(pos.x, pos.y, dist * 0.5); camera.lookAt(pos);
I've read about using
geometry.center()
to translate an object's coordinates back to the origin, but the oldTHREE.GeometryUtils.center
has been replaced bygeometry.center()
and I keep encountering errors when attempting to implement it.Since geometry is now replaced by bufferGeometry when loading OBJs, I'm struggling to convert bufferGeometry into geometry to utilize the
center()
function. Do I need to place this in a loop within the object traversal > child loop? It all feels overly complex.geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
My current code simply involves an OBJLoader:
var objLoader = new THREE.OBJLoader();
objLoader.setPath('assets/');
objLoader.load('BasketballNet_Skull.obj', function (object) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = material;
}
} );
scene.add(object);
});
(By the way, this is my first time posting a question on Stack Overflow, so please excuse any formatting or beginner mistakes)