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

Position perspective camera to center object group on screen (not .LookAt(...))

Discussion in 'General Discussion' started by larku, Oct 19, 2019.

  1. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Hey, looking for some advice on how to position a perspective camera to center a group of object on screen.

    So given a camera which has a fixed rotation and fixed FOV I want to move the camera position such the my selected list of GameObjects are centered in the view.

    The camera rotation is fixed (must stay the same). The group of objects can change in size, when this happens we want to find where the center of that group of objects is, move the camera such that it is now centered on the group and then calculate the required FOV to fit the group of objects in the screen.

    All is solved except finding the camera position to center the group. In reality there are 3 cameras (only one active at a time) with different rotations and positions. I'm hoping for a one-size-fits-all type solution. For cameras that are perpendicular to the group this is simple since the center of the encapsulated bounds is also the center of the group for the camera. This is not true for rotated cameras.

    I've tried using the extents mapped to screen space, determining the screen and world points that "bound" the object, finding that center and projecting that either into the world or the camera's near clip pane. This doesn't work particularly well either.

    We could brute force it through an iterative search, but this becomes too expensive to do at the time and frequency we need this.

    Any ideas?
     
  2. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,617
    It'd be handy if we had some images of the problem scenarios, so we had some clue of the problems you're running into or why you're unhappy with the results.

    At the moment I'm also wondering how many objects are in the group that a "brute force" solution can't work. Even in that case, first find a solution that gets the desired results and then figure out how to make it faster.

    Also... why not the Scripting section?
     
  3. steego

    steego

    Joined:
    Jul 15, 2010
    Posts:
    969
    I think Cinemachine can do this automagically for you.
     
    angrypenguin and Ryiah like this.
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,965