Unity: UI Space Conversion

Converting between the different coordinate systems of the Unity UI can be the key to a lot of cool custom UI and input features. You can basically convert every point in all coordinate spaces available with a few simple math functions. There are three different spaces:

 

Screen Space

This is the space in which Unity provides its Input, for example, the position returned by Input.mousePosition is in screen space. Points in screen space are Vector2 and contain x- and y-pixel coordinates of the screen. Some of Unity’s input functions will return Vector3 instead of Vector2 for calculation convenience. The z value of these points is always 0. The origin of this coordinate system is the lower-left corner and its size is the pixel size of the device/window.

 

Be aware that the mouse position can leave the screen space when your game is played in window mode and the user moves the mouse out of the window.

 

Don’t be afraid to use screen space coordinates that are outside of the visible screen area. For example points with coordinates smaller than 0 or larger than the screen size. Unity will handle all invisible positions correctly and you can use them to spawn objects right off-screen.

 

public static Vector3 ScreenToViewPort(Vector3 screenPosition)
{
  return new Vector3(
    screenPosition.x / Screen.width,
    screenPosition.y / Screen.height,
    0); 
}

 

View Port Space

This is basically the same as screen space but normalized to the screen size. The origin of the coordinate system is also the lower-left corner but the size is 1 in each dimension.

 

You can convert between the two spaces by dividing or multiplying the position.

 

public static Vector3 ViewPortToScreen(Vector3 viewPortPosition)
{
  return new Vector3(
    viewPortPosition.x * Screen.width,
    viewPortPosition.y * Screen.height,
    0);
}

 

Rect Space

It’s best practice to use Unitys build-in RectTransformUtility to convert between screen and rect space. It contains the following functions:

 

PixelAdjustPoint

Convert a given point in screen space into a pixel correct point.

 

PixelAdjustRect

Returns the pixel coordinates of the rect transform corners.

 

RectangleContainsScreenPoint

Returns whether a screen point is contained in the rect transform.

 

ScreenPointToLocalPointInRectangle

Transform a screen point to a position in the local space of a rect transform.

 

ScreenPointToWorldPointInRectangle

Transform a screen point to a position in world space that is on the plane of the given rect transform.