- Home /
How to make the camera show only the part of the world which is in a specified rectangle?
Hello,
In my game, I have code which determines a bounding box that encloses all the players in the game:

The bounding box is defined by four float numbers, xmin, xmax, ymin, ymax (which is effectively a Rect).
I want the camera (I'm using orthographic) to show only as much of the game world as the bounding box encloses. Every frame, as player positions change, the bounding box is recalculated accordingly, and so should the camera. I expect smooth changes in the camera since the box is also updated gradually, once per frame.
I tried to accomplish the desired camera motion by changing the camera's orthographicSize or its position as follows:
Camera.main.transform.position = new Vector3(m_Viewport.center.x, m_Viewport.center.y, -1);
Camera.main.orthographicSize = 0.5f * m_Viewport.height;
m_Viewport is a Rect that is my bounding box.
The first line matches the center of the bounding box with the camera position. The second line is based on the fact that the orthographic size is half the height in game units.
While the position seems to work OK, the zooming behaviour (`orthographicSize`) is off. Only by moving the camera to the center of the bounding box I can't achieve the behaviour that only the inside of the box be seen; things outside are also captured by the camera. I believe the orthographicSize is the culprit but how do I choose the right value for it?
Thanks, Rokas
I'm not 100% on one thing... do you want it to appear bordered like the image where everything outside the rect is empty space, or do you want to zoom the camera to make the screen represent the rect?
I want to zoom the camera to make the screen represent the rect.
Your answer
Follow this Question
Related Questions
How to properly set camera sizes in 2D Ortho camera split screen? 0 Answers
Camera zoom AND smooth transition? 0 Answers
Camera preview only shows skybox 7 Answers
How to make a split screen, one for a main camera and one for the VR set camera? 1 Answer
My Scene View is Fine but my Game View is just black but the Camera Works 0 Answers