Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Ensure All GameObjects Are Visible Within Camera Frame

Discussion in 'Scripting' started by gretty, Aug 10, 2014.

  1. gretty

    gretty

    Joined:
    Jun 20, 2012
    Posts:
    72
    Hello

    How do you make a camera position itself so all GameObjects are in frame?

    For example; I have many GameObjects that represent pipes, pits, roads, etc. and they all sit on a Terrain. I want to make my camera sit with a birds eye view (look straight down) and show all these GameObjects.

    But the most important thing is that all GameObjects are visible within the camera frame.

    Any ideas how I can do this?

    A very inefficient way could be:
    - Position the camera at (0, 1, 0) and rotate it so its looking straight down
    - Move the camera up on the Y axis
    - Make each GameObject listen to the OnBecameVisible() method. When all GameObjects have received a OnBecameVisible() event I know all GameObjects are visible and should stop moving the camera up on the Y axis.


    But thats a little hacky, any other ideas how I can do this?
     
  2. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    If you can find the 4 extreme positions to visualize (top,left, bottom, right) then you can check with camera.WorldToScreenPoint (target.position) if they are in the view rect.
     
  3. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    Perhaps you can use this to position the camera if you know at least the height of the frustum:

    Code (CSharp):
    1.  
    2. float DistanceForHeightAndFov(float height, float fov)
    3. {
    4.     return height * 0.5f / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);
    5. }
    6.