To ensure that your entire scene fits within the view of your current camera, adjustments can be made to the variables of an OrthographicCamera
including left, right, top, bottom, near,
and far
. It is important to maintain the relationship left = -right
and top = -bottom
, while also ensuring the aspect ratio matches that of the window. This essentially involves modifying a single scale value.
Rather than individually processing all points in the scene, a more efficient approach is to approximate the scene with a bounding sphere of radius r
centered at point c
. By calculating these properties beforehand or storing them with the scene, the focus shifts from fitting the scene to ensuring the entire bounding sphere is visible within the view.
For an orthographic camera, determining the bounds is straightforward. Transforming the sphere's center into camera coordinates is a key step:
var cInCameraSpace = new THREE.Vector3(); //initialize this once
//transform sphere center to camera space
cInCameraSpace.copy(c);
cInCameraSpace.applyMatrix4(camera.matrixWorldInverse);
The bounds can then be calculated as follows:
var halfWidth = Math.abs(cInCameraSpace.x) + r;
var halfHeight = Math.abs(cInCameraSpace.y) + r;
camera.near = -cInCameraSpace.z - r;
camera.far = -cInCameraSpace.z + r;
Next, ensuring the aspect ratio is maintained based on the window's aspect ratio, denoted as windowAspect
, is crucial:
if(halfWidth / halfHeight > windowAspect) {
camera.right = halfWidth;
camera.top = halfWidth / windowAspect;
} else {
camera.top = halfHeight;
camera.right = halfHeight * windowAspect;
}
camera.bottom = -camera.top;
camera.left = -camera.right;