Adjusting camera for visible Three.js shape

后端 未结 2 1237

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();
    }
    
    0 讨论(0)
  • 2020-12-06 04:05

    Perspective Camera. If the camera is centered and viewing the cube head-on, define

    dist = distance from the camera to the front face ( important ! ) of the cube

    and

    height = height of the cube.

    If you set the camera field-of-view as follows

    fov = 2 * Math.atan( height / ( 2 * dist ) ) * ( 180 / Math.PI );
    

    then the cube height will match the visible height.

    Orthographic Camera. If the camera is centered and viewing the cube head-on, define

    aspect = the aspect ratio of your window (i.e., width / height)

    and

    height = height of the cube.

    Then construct your camera this way:

    camera = new THREE.OrthographicCamera( -aspect * height/2, aspect * height/2, height/2, -height/2, near, far );
    

    The cube height will match the visible height.

    In either case, if the camera is not centered, or is otherwise viewing the cube at an angle, then the problem is more complicated.

    Also, if the window is narrower than it is high, then the width is the constraining factor, and the problem is more complicated.

    0 讨论(0)
提交回复
热议问题