Search code examples
three.jscameragltf

Centering pivot point in three.js with OrbitControls autorotate


I'm loading a .glb model into three.js, and while I have it rotating automatically using OrbitControls, I'm not able to see how to change the pivot point so the rotating model is centered.

I've seen a lot of questions on setting boxes or pivot points with rotation, but not with OrbitControls and autorotate. Is there a way for me to center the imported model using autorotate as per my code below?

var scene = new THREE.Scene(); 

 // Load Camera Perspective
var camera = new THREE.PerspectiveCamera( 25, window.innerWidth / window.innerHeight, 1, 8000 );
camera.position.set( 200, 100, 0 );

 // Load a Renderer
var renderer = new THREE.WebGLRenderer({ alpha: false });
renderer.setClearColor( 0xC5C5C3 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

 // Load the Orbitcontroller
var controls = new THREE.OrbitControls( camera, renderer.domElement ); 

camera.position.set( 60, 20, 100 );
controls.update();

controls.autoRotate = true;

controls.minDistance = 700;
controls.maxDistance = 2000;
//controls.update();

 // Load Light
var ambientLight = new THREE.AmbientLight( 0xcccccc );
scene.add( ambientLight );

var directionalLight = new THREE.DirectionalLight( 0xffffff );
directionalLight.position.set( 0, 1, 1 ).normalize();
scene.add( directionalLight );              

 // glTf 2.0 Loader
var loader = new THREE.GLTFLoader();                
loader.load( 'BTR.glb', function ( gltf ) {                  

var object = gltf.scene;                
gltf.scene.scale.set( 1, 1, 1 );               
gltf.scene.position.x = 0;                  //Position (x = right+ left-) 
gltf.scene.position.y = 0;                  //Position (y = up+, down-)
gltf.scene.position.z = 0;                  //Position (z = front +, back-)

scene.add( gltf.scene );

}); 

function animate() {

    // required if controls.enableDamping or controls.autoRotate are set to true
    controls.update();
    render();
    requestAnimationFrame( animate );
    }

function render() {

    renderer.render( scene, camera );
    }

render();
animate();

Solution

  • I think this issue can be solved by setting Controls.target (the focus point) to the center point of your glTF asset. You should be able to do this like so:

    var aabb = new THREE.Box3().setFromObject( gltf.scene );
    aabb.getCenter( controls.target );
    controls.update();
    

    three.js R107