Position PerspectiveCamera and OrbitControls on to a GLTF scene

I have a simple (empty) scene that I want to use for displaying GLTF 3D assets.

After I’m using GLTF loader I want to position the camera so it would point to the model on my gltf.scene.

Also, I would like to limit the OrbitControls (or the PerspectiveCamera) so it wont allow the user to collapse with the asset from the gltf.scene and wont be able to move to far away from the asset.

How can I calculate the fov,near and far according to the mesh / objects on the gltf.scene?

Once you’ve loaded the glTF file and added it to the scene, it no longer matters what type of file it was — it’s just an instance of THREE.Scene, containing THREE.Object3D and THREE.Mesh instances. See docs on THREE.Object3D for the API available. You may want .lookAt() in particular.

Some code I’ve used in another project:

object.updateMatrixWorld();
const box = new THREE.Box3().setFromObject(object);
const size = box.getSize().length();
const center = box.getCenter();

object.position.x += (object.position.x - center.x);
object.position.y += (object.position.y - center.y);
object.position.z += (object.position.z - center.z);
controls.maxDistance = size * 10;
this.defaultCamera.position.copy(center);
this.defaultCamera.position.x += size / 2.0;
this.defaultCamera.position.y += size / 5.0;
this.defaultCamera.position.z += size / 2.0;
this.defaultCamera.near = size / 100;
this.defaultCamera.far = size * 100;
this.defaultCamera.updateProjectionMatrix();
this.defaultCamera.lookAt(center);

There are similar settings for OrbitControls.

2 Likes

Terns out const size = box.getSize().length(); is 0 in my case so if that’s the case I’m just using size = 1; witch works fine for me.

I’ll be sure to check that code in several models in update here.

Thank you for your answer.

The code works but not exactly like I’ve copied it to my project.
instead of this code:

const box = new THREE.Box3().setFromObject(object);
const size = box.getSize().length();

I’ve used this one:

var maxSize = 0;
for (var i = 0; i < scene.children.length; i++) {
   var box = new THREE.Box3().setFromObject(scene.children[i]);
   var size = box.getSize().length();
   if (size > maxSize)
      maxSize = size;
}

if (!maxSize)
   maxSize = 1;

Thank you.