I need to frame the scene like in the editor F key does. Is there a simple function or algorithm for this?
One way I thought of is to move the camera behind all the objects then move the camera back in Update, and freeze it after all the gameobjects have fired OnBecameVisible.
Is there a better way?
Perhaps you can walk the geometry collection, determine the maximum bounding coordinates from the camera’s point of view (get verts in world coords, convert to camera relative coords, trap max x/y/z values) then zoom out until a box of that size is visible?
Lots of talk, no immediate code to share, am I making sense?
Tom
Now I am doing similar to what you suggest, using Bounds.Encapsulate to get the center of a hierarchy of objects. This makes it easy to point the camera at it, using LookAt. There is a thread here that was helpful too:
http://forum.unity3d.com/viewtopic.php?t=4954&highlight=encapsulate
So this is working well for me.
Now I have to figure out how to adjust the height of the camera so it is nicely framed and not too close or far. I am going to try to figure out the geometry of that. I think knowing the bounds and the field of view of the cam, it should be just a simple formula.
I haven’t tested it but I guess that Renderer.OnBecameVisible will fire when the object is only partially in view which isn’t really what I want.
Anyways thanks for your reply!
If you make an encapsulating sphere instead of a box, the distance the camera must be from the center to show the entire sphere is:
distance = sphere.radius / Mathf.Abs( Mathf.Sin(Camera.fieldOfView*Mathf.Deg2Rad / 2) );
Assuming, of course, that the camera is looking at the center.
And on a hacky side note: The easiest way to make an encapsulating sphere is to just take the diagonal of the boundingbox and use that as diameter (the center is obviously the same). This will produce a sphere which is somewhat to large, but it’s fast and easy (usually I just subtract a fudge-factor from the diameter to compensate :-))
Talzor, many thanks. Using your formula, I am skipping the sphere actually and for the radius I am using using half of the distance of the diagonals of the Bounds, scaled by a fudge factor. This works!