Adjusting camera for visible Three.js shape

后端 未结 2 1236

I have a CubeGeometry which the camera is looking at, and I want the camera to zoom so that the cube is entirely visible, but no larger.

My initial attempt was to co

2条回答
  •  [愿得一人]
    2020-12-06 03:48

    Multiplying by camera.matrixWorldInverse gives a vector in the camera's coordinates, but importantly does not apply perspective.

    function toCameraCoords(position) {
      return camera.matrixWorldInverse.multiplyVector3(position.clone());
    }
    

    We can then find the smallest angle that will fit all the box corners in the scene. arctan(D.x / D.z) gives the angle BCD where B is what the camera is looking at, C is the camera's position, and D the position of an object that you want to be visible in the camera coordinates.

    In my case, the following ensures that the the cube boundbox is fully visible.

    function ScaleInView() {
      var tmp_fov = 0.0;
    
      for (var i=0; i<8; i++) {
        proj2d = toCameraCoords(boundbox.geometry.vertices[i]);
    
        angle = 114.59 * Math.max( // 2 * (Pi / 180)
          Math.abs(Math.atan(proj2d.x/proj2d.z) / camera.aspect),
          Math.abs(Math.atan(proj2d.y/proj2d.z))
        );
        tmp_fov = Math.max(tmp_fov, angle);
     }
    
     camera.fov = tmp_fov + 5; // An extra 5 degrees keeps all lines visible
     camera.updateProjectionMatrix();
    }
    

提交回复
热议问题