A Quick Look at Calculating a Camera's Size in Unity



When making 2D games in Unity one thing that may be required to know is the size of the camera. In Unity we know orthographicSize will provide us with the vertical boundary of the camera that relates to the size value set in the camera’s inspector. The horizontal size of the camera isn’t given as this depends on the aspect ratio used for the game.

If you want to know the horizontal size of the camera, for instance to create a transition between areas in a level once a character hits the edge of the screen. A simple approach would be given the width of the screen in pixels and the position of the character in pixels we know once character x position = screen width we can determine that the player is at one edge of the screen. This approach however, doesn’t factor in different screen resolutions, and only works for a single resolution.​

A better approach is to make use of the camera size which is independent of the screens resolution. As previously mentioned the vertical size is already given to use through the variable orthographicSize however the horizontal value isn’t. To calculate this, we need to know the vertical size and aspect ratio.

​The aspect ratio defines the relationship between the width and height of an image. When making a game we want to know the aspect ratio of the devices screen, this can be determined by using the resolution of that device that corresponds to width and height of the screen in pixels. Given a resolution of 480×800 we would have an aspect ratio of 3:5, 1920×1080 has a 16:9 aspect ratio, 980×540 also has the ratio 16:9 however the pixel width and height is halved.

Dividing one side by the other we can determine the “difference” between the width and height of the screen. Given that we have the vertical size we can calculate the horizontal size through the following:​

horizontalSize = verticalSize * (screenWidth / screenHeight);

The value given by calculating the aspect ratio (screenWidth / screenHeight) will produce a value that when multiplied with the verticalSize will either scale verticalSize up or down, dependent on whether screenWidth is larger or smaller than screenHeight.​

The result is a value that gives the horizonatlSize of the camera. Going of the previous example this value can now be used to determine when the character is on the edge of the screen, positive value for the right side, and a negative value for the left.