Posts Tagged ‘size’

Unity: Getting screen size in units (2D)

Wednesday, January 14th, 2015

When doing 2D games in Unity it is often handy to know where the borders of the screen are in units so one can for example spawn units on the edge of the screen or detect when something leaves it.

Fortunately it’s easy to figure out when using orthographic camera.

Camera.main.orthographicSize is always half of the total screen height, with the width changing with the aspect ratio. You can get the top or bottom coordinates by adding/subtracting it to/from the camera’s y position.

For the width you can then multiply the aspect ratio with the orthographic size,
camera.orthographicSize * Screen.width/Screen.height , to get half of the total screen width.

You can then get the x position of the screen’s left border like this:

float leftSideOfScreen = Camera.main.transform.position.x - Camera.main.orthographicSize * Screen.width / Screen.height;