Working with the coordinate system and game screen in Unity 2d?

 ̄綄美尐妖づ 提交于 2019-12-03 02:15:07

There are three coordinates systems in Unity: Screen coordinates, view coordinates and the world coordinates.

World coordinates: Think of the absolute positioning of the objects in your scene, using "points". You can choose to have the units represent any length you want, for example 1 unit = 10 meters. What is actually shown on the screen is determined by where the camera is placed and how it is oriented.

View Coordinates: The coordinates in the viewport of a given camera. Viewport is the imaginary rectangle through which the world is viewed. These coordinates are porportional, and range from (0,0) to (1,1).

Screen Coordinates: The actual pixel coordinates denoting the position on the device's screen.

Note that the world co-ordinates of any given object will always be the same regardless of which camera is used to view, whereas the view coordinates depends on the camera being used. The screen coordinates in addition depend on the resolution of the device and the placement of the camera view on the screen.

The "Camera" object provides several methods to convert between these different coordinate systems like "ScreenToViewportPoint" "ScreenToWorldPoint" etc.

Example: Place object on top left of screen

    float distanceFromCamera = 10.0f;
    Vector3 pos = Camera.main.ScreenToWorldPoint (new Vector3 (0, Screen.height, distanceFromCamera));

    transform.position = pos;

The ScreenToWorldPoint function takes a Vector3 as an argument, where the x and y denote the pixel position on the screen ( 0,0 is the bottom left) and the z component denotes the desired distance from the camera. An infinite number of 3D locations can map to the same screen position, so you need to provide this value.

Just make sure that the desired position falls within the clipping region of the camera. Also, you might need to pick a proper pivot for your object depending on which part of your object you want centered on the top left.

Using:

Camera.main.WorldToScreenPoint (transform.position);

Let's me convert my GameObjects tranform position to the screen's x and y coordinate system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!