简体   繁体   中英

Camera Smoothly Zoom Into Object Position On Mouse Click

So I have a scene with multiple boxes and a PerspectiveCamera.

I'd like to achieve this effect whenever I click on a specific box.

  • The camera will smoothly transition from its current position to the box's position
  • The box is centered in the camera's viewport
  • The camera will smoothly zoom in and focus on the box

This effect was inspired by 100,000 Stars . Whenever a user would click on a star, the camera would zoom into the star and display it in the center. I'm trying to replicate that effect.

I'm currently able to grab the box's position and look at it. But I want to do more than that and I'm unsure how to proceed.

I think what you need is an animation, there are many animation libraries like anime.js and tween.js . As you have grabbed the position after translating, you can make an animation to smooth your translation. Here is a snippet with tween.js:

var tween2 = new TWEEN.Tween(camera.position)
                .to({
                    x : target.position.x,
                    y : target.position.y,
                    z : target.position.z
                } , 1000)
                .easing(TWEEN.Easing.Linear.None)
                .start();

If you want to locate the box on the center of your camera. we also need to change the camera rotation. Here is a way to compute the target rotation by using matrix.

    var rotation_matrix = new THREE.Matrix4();
    rotation_matrix.lookAt(target_position,target_box.position,camera.up);
    var target_rotation = new THREE.Euler(0,0,0,"XYZ");
    target_rotation.setFromRotationMatrix(rotation_matrix);
    //now, the target_rotation would be the rotation after translating.

Then, you can use the same way to make an animation to change the rotation.

BTW, It seems in 100000 stars they switch camera in the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM