4

I am trying to make an object fit inside the camera frustum, and I went through all the trigonometry for that, and this is the code I used.

var setupCamera = function() {
    aspectRatio = window.innerWidth / window.innerHeight
    camera = new THREE.PerspectiveCamera( 45, aspectRatio, 1, 10000 );
    scene.add(camera);
}

var updateCamera = function() {
    var height = mesh1_BB.max.y;

    var width = mesh1_BB.max.x - mesh1_BB.min.x;
    var vertical_FOV = camera.fov * (Math.PI/ 180);

    var max_z = mesh1_BB.max.z;

    var horizontal_FOV = 2 * Math.atan (Math.tan (vertical_FOV/2) * aspectRatio);

    var distance_vertical = height / (2 * Math.tan(vertical_FOV/2));
    // alert ('vertical' + distance_vertical);
    var distance_horizontal = width / (2 * Math.tan(horizontal_FOV/2));
    // alert ('horizontal' + distance_horizontal);
    var z_distance = distance_vertical >= distance_horizontal? distance_vertical : distance_horizontal;

    camera.position.z = z_distance + max_z;
    camera.position.y = 0 ;
    camera.position.x = 0;
}

While I think the calculation for the camera distance is correct, this is the result I get: enter image description here

I thought the issue was changing the y position of the camera, and put it up with camera.position.y = height; but then this is what I get:

enter image description here

The result I want is the following (which is something I obtained by panning with the right-click button of the mouse and dragging it up until it fitted the whole canvas frame): enter image description here

I really hope you can help with this because this has been driving me crazy all day long ;-)

Thanks a lot!

1

1 Answer 1

2

I have not checked your distance calculations, but you looking straight down the z-axis, while the object isn't vertically centered around 0. Putting your camera.y at mesh1_BB.max.y / 2 should fix that.

If you don't want to move your camera, at least point it towards the actual center of the object. In that case, using the (axis aligned) bounding box isn't 100% correct anymore.

2
  • Thank you very much for your fast answer. I did change the camera.y to mesh1_BB.max.y /2 but then the result I get is something quite similar to the second image in the original post. While experimenting and putting a very big camera.y, the camera keeps pointing at (0,0,0). I think it is part of the issue, the camera should point upfront and not to 0,0,0...
    – jhagege
    Commented Aug 18, 2014 at 17:10
  • TrackballControls was messing with my camera properties. Setting it at height/2 does the job greatly, thank you so much!!!
    – jhagege
    Commented Aug 18, 2014 at 17:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.