THREE.js fit Orthographic camera to scene

2019-06-12 21:50发布

问题:

I've searched through many related questions on stack overflow, but I couldn't quite find the answer to this problem.

I have a big, dynamic group of Object3D's in my scene, with an orthographic camera looking at them head-on.

I want to have a simple function which, when called, will simply match the top/left/bottom/right/zoom properties of the Orthographic camera to properly fit the Object3D group.

I've tried all kinds of things, but none of my code is worth posting. I need to look at this from a whole new angle (pun intended). I have found various other answers which discuss changing the fov of the camera, once you know the distance from the face of bounding box of the group to the camera, but I don't know how to implement that with an orthographic camera, since (as far as I've tried) the fov property doesn't work with it (maybe it actually does, I just don't know).

So I don't particularly like asking for code, but nevertheless I would like a function which would automatically adjsut the appropriate properties of the Orthographic camera to fit the object passed to it as a parameter, for example:

function fitOrthographicCameraToObject3DGroup(group) {
    //implement here (my question)
}

回答1:

Setting the top/left/bottom/right of the orthographic camera once you have the bounding box should not be a problem. Just take the half lengths of the bounding box.

The zoom is the issue and for that you can confine your scene in a unit cube by scaling up or down your scene by the appropriate amount depending on your bounding box size. Then you dont have to worry about the zoom and the above top/left/bottom/right values become 0.5/0.5/-0.5/-0.5.



回答2:

Calculate the bounding box of your mesh and apply this code. This works for me

        var camera = new THREE.OrthographicCamera(container.offsetWidth / -2, container.offsetWidth / 2, container.offsetHeight / 2, container.offsetHeight / -2, 100, 100000);

        //For centering the meshGroup
            var box = new THREE.Box3().setFromObject(meshGroup);
            box.center(meshGroup.position);
            meshGroup.localToWorld(box);
            meshGroup.position.multiplyScalar(-1);

       //For fitting the object to the screen when using orthographic camera

           Camera.zoom = Math.min(container.offsetWidth / (box.max.x - box.min.x),
                container.offsetHeight / (box.max.y - box.min.y)) * 0.4;
           Camera.updateProjectionMatrix();
           Camera.updateMatrix();