Object instantiation accurately inserted into clipping camera in Three.Js

I am trying to make an object fit inside a clipping camera and I went through all the trigonometry for this 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 problem was changing the y position of the camera and exposing it with the camera .position.y = height; but then this is what I get:

enter image description here

As a result, I want the following (this is what I got by panning with the mouse with the right mouse button and dragging up until it has set the entire canvas frame): enter image description here

I really hope you can help with this, because it drove me crazy all day; -)

Thank you so much!

+3


source to share


1 answer


I haven't checked your distance calculations, but you are looking straight down the z-axis, while the object is not vertically centered around 0. Putting your camera.y

in mesh1_BB.max.y / 2

should fix that.



If you don't want to move the camera, at least point it to the actual center of the subject. In this case, the use of the bounding box (axis-aligned) is no longer 100%.

+1


source







All Articles