Moving camera so that a plane is fitted to its view

What I want to do is move a camera using C# to a position that ensures that a plane is fully visible in its view (centered and as close to the edges of the screen as possible).

The camera and plane should be able to have any position/rotation before the move. However only the camera’s position can be changed, not its rotation. The plane must not be moved/rotated at all.

Here are before and after images that I hope illustrates exactly what I want to happen after the script has been executed.

Image 1: Original position and rotation of the camera.


Image 2: The camera has been repositioned. Its rotation has not been modified.

Keep in mind that the plane can have any rotation and size (its width does not always equal its height) and the camera does not always have the same rotation. If possible I’d like the script also work if the camera is filming towards the back of the plane.

Bump

Bump

You spouted out a list of requirements and then essentially said “so, get to work guys!”. That’s not actually going to happen- this board is for support, not writing scripts for you. I’d suggest you google and/or check the AssetStore for the kind of thing that you want and, if you can’t find it either of those ways, then either trying to do it yourself or hiring someone to do it for you. If you run into a specific, quantifiable problem as you work on this yourself, then we can help you out.

Just to get you started, the solution is very likely going to involve calculating a list of “extents” for the object you want to keep in the screen- points that form the “corners”, easy enough for planes or cubes, or some simile of “corners” in complex shapes by combining the smallest and largest x and y and z values for that object’s mesh/collider in all possible combinations.

You put all of those in a list, then you iterate over them using, probably, WorldToScreenPoint. If the results say that the extent is beyond the screen view (less than 0 or greater than screen.width or screen.height), then you’ll want to lerp the camera in that direction, and/or zoom out in the case that extents are simultaneously “beneath” and “above” / “left” and “right” of the screen view. It’s going to be complicated and messy and take a lot of fidgeting to get it to work how you want it to, so be prepared.

1 Like

You can use mesh bounds and do the math from there.

I use Camera.ViewportPointToRay(new Vector3(0.5f,0.5f,0)) to calculate the focus point of the camera. and then adjust the camera position