Orthographic Camera - show all of the object

I have an Orthographic camera setup to look at a dynamic collection of objects (these are the only objects in the scene) and I would like to ensure that all the objects appear without any clipping within the view. My working assumption is to create a container object that houses all the objects and check against that single object. So, how do I script the camera metrics to give me the desired view?

worth noting, it might be easier, rather than doing all this, to just dynamically place your objects within the known confines of a fixed camera position, but I’ve answered assuming you’re wanting to do some kind of dynamic camera that zooms in/out to keep a moving set of objects in-scene.

As you said, you’ll only need to determine the bounds x/y (or x/z, or whatever axes you’re viewing along). If you already have that covered, you can skip this next bit. You can just use the bounding boxes unity builds; you can get them transformed into world space from each object’s MeshRenderer component as so…


(if you’re using something other than meshes(?), anything using a standard unity Renderer will have the bounds member, as it’s essential to the render process.)

Just create your own bounds object, then loop through the obejcts in the scene. You can use the encapsulate method on Bounds to expand it to include each object’s bounds.

In **pseudo-**unityscript…

 for (object in allObjects)

Then just center the camera’s position at the center of the combined bounding box (just on x/y, of course, still needs to be pulled away from the scene on z, or whichever axis it’s viewing along).

Last thing, you’ll have to check the aspect ratio of the bounding box to calculate orthographicSize. Just calculate the true aspect ratio of the box, dividing width by height. If it’s less than or equal to your game’s aspect ratio, you’re can just use the y component of your bounding box’s extents.y. If it’s greater, you’ll need to calculate a new one or some objects will be outside the left/right edges of the scene. That’ll be easy, though; just calculate a new extent as (totalBounds.extents.x / desiredAspectRatio).
Set that to your camera’s orthographicSize, and you’re set! You might want to pad it a bit, multiplying the final value by 1.15 or some such value, tweaked to give the desired results, so that the outermost objects aren’t actually touching the edges of the screen.

The code will be a lot shorter than this explanation. Hope it’s clear and not overly confusing!