camera to face selected plane three.js

303 views Asked by At

i have 600 planes being added to a scene in random x,y,z positions, each plane is clickable. when clicked i animate to the selected plane. All works but i am struggling for the camera to face the selected plane / or make sure the plane is centred in the view. I have tried getting the direction vector of the clicked item but not sure how make sure the camera is always a set distance away. here is the function and below a link to the test. Any ideas? Many thanks http://adigitalengagement.co.uk/webauth_stickies/plane/

    function toObj(obj) {

    var lookAtVector = new THREE.Vector3(0, 0, 1);
    lookAtVector.applyQuaternion(obj.quaternion);
    console.log(lookAtVector);
    var rotateTween = new TWEEN.Tween(controls.target)
        .to({
            x: obj.position.x,
            y: obj.position.y,
            z: obj.position.z
        }, 4000)
        .interpolation(TWEEN.Interpolation.CatmullRom)
        .easing(TWEEN.Easing.Quintic.InOut)
        .start();

    var goTween = new TWEEN.Tween(camera.position)
        .to({
            x: obj.position.x,
            y: obj.position.y,
            z: obj.position.z + 10
        }, 4000)
        .interpolation(TWEEN.Interpolation.CatmullRom)
        .easing(TWEEN.Easing.Quintic.InOut);

    goTween.start();
    goTween.onComplete(function() {
        console.log('done!');

    });


}
1

There are 1 answers

0
prisoner849 On BEST ANSWER

I'm sure there can be a better solution, but this one can be a starting point based on this SO answer. I've changed your toObj() function and added a global variable:

var lookAtVector = new THREE.Vector3(0,0,0);
...
function toObj(obj) {
var normalMatrix = new THREE.Matrix3().getNormalMatrix( obj.matrixWorld );
var worldNormal = new THREE.Vector3(0,0,1).applyMatrix3( normalMatrix ).normalize();
var camPosition = new THREE.Vector3().copy(obj.position).add(worldNormal.multiplyScalar(100));

var rotateTween = new TWEEN.Tween(lookAtVector)
    .to({
        x: obj.position.x,
        y: obj.position.y,
        z: obj.position.z
    }, 4000)
    .easing(TWEEN.Easing.Quadratic.InOut)
    .onUpdate(function(){
        camera.lookAt(lookAtVector);
    })
    .onComplete(function(){
        lookAtVector.copy(obj.position);
    })
    .start();

    var goTween = new TWEEN.Tween(camera.position)
    .to(camPosition, 4000)
    .easing(TWEEN.Easing.Quadratic.InOut)
    .start();
}

jsfiddle example