1. 程式人生 > 實用技巧 >Unity中的座標系

Unity中的座標系

一:Unity中的四種座標系

在這裡插入圖片描述
——世界座標(World Space)
世界座標很好理解,它是一個3D座標。就是遊戲物體在你創造世界中的座標。transfrom.position獲得的是物體相對於世界座標的位置,transfrom.localPosition獲得的是物體相對於父物體座標的位置
模型Mesh儲存的頂點座標均為區域性座標系下的座標

——螢幕座標(Screen Space)
螢幕座標是以畫素來定義的,與解析度有關,例如解析度為1280*720的螢幕則Screen.width為1280,Screen.height為720。
Screen.width = Camera.main.pixelWidth和Screen.height = Camera.main.pixelHeight只有在相機視口座標是整個螢幕時才滿足。所以不難看出Screen.width是螢幕的解析度即螢幕的寬度, 而Camera.main.pixelWidth是相機的視口畫素大小,也可以理解為相機視口的畫素寬度。

螢幕的左下角座標為(0 , 0),右上角為(Screen.width , Screen.height),z軸座標是相機的世界座標中z軸的負值
我們常用的Input.mousePosition和移動端的Input.GetTouch(0).position都是獲得的游標在螢幕座標的位置

——視口座標(Viewport Space)
視口座標系其實就是將螢幕座標系單位化
視口座標的左下角為(0 , 0),右上角為(1 , 1),z軸座標是相機的世界座標中z軸的負值
可用於製作分屏遊戲
在這裡插入圖片描述

——GUI座標
只作瞭解就好
它的原點在左上角為(0,0),右下角座標為(Screen.width, Screen.height), 因為這是一個二維的座標系,所以座標z的值永遠都為0

二:各種座標轉換

——InverseTransformPoint和TransformPoin
例如物體A的世界座標座標為(1,2,3),物體B的世界座標為(2,2,2),現在需要計算物體B相對於物體A的區域性座標,則應該使用A.transform.InverseTransformPoint(B)

——螢幕座標轉世界座標
Vector3 mousePos = Input.mousePosition;
Vector3 screenToWorld = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, -Camera.main.transform.position.z));

Debug.Log(screenToWorld);

——世界座標轉螢幕座標
Vector3 worldToScreen = Camera.main.WorldToScreenPoint(transform.position);
Debug.Log(worldToScreen);

——螢幕座標轉視口座標
Vector3 mousePos = Input.mousePosition;
Vector3 screenToViewport = Camera.main.ScreenToViewportPoint(mousePos);
Debug.Log(screenToViewport);

——視口座標轉螢幕座標
Vector3 viewportToScreen = Camera.main.ViewportToScreenPoint(new Vector3(1, 1, 0));
Debug.Log(viewportToScreen);

——世界座標轉視口座標
Vector3 worldToViewport = Camera.main.WorldToViewportPoint(transform.position);
Debug.Log(worldToViewport);

——視口座標轉世界座標
Vector3 viewportToWord = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, -Camera.main.transform.position.z));
Debug.Log(viewportToWord);

——螢幕座標轉UI座標
Vector2 mousePos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent.GetComponent(), Input.mousePosition, null, out mousePos);
Debug.Log(mousePos);

1.Canvas的RenderMode為Overlay時,cam引數應該為NULL。
2.rect必須為直接父物體

任何一個座標轉世界座標時,z的引數都應該為相機在世界座標中z的負值
從世界座標轉到任何一個座標時,計算出的z值都是相機的世界座標中z軸的負值

三:螢幕座標轉世界座標時為什麼要使用-Camera.transform.position.z

任何一個座標轉世界座標時的z值,可以理解為離相機的距離。其實是把螢幕座標投影到相機的視錐體平面上,如果z的值為0,則相當於投影到了相機的近平面上,但是近平面的最小值為0.01,所以在進行螢幕座標轉世界座標時,螢幕座標的z值不能為0(注意Input.mousePosition的z值為0)
而且隨著z的值越來越大,投影到的平面也會越來越大,x和y的值也會越來越大