世界坐標系就是unity的左手坐標系
屏幕坐標系是Game視圖相機拍攝的場景坐標系,左下角(0,0),右上角(Screen.width,Screen.height),單位是像素。Z的位置是以相機的世界單位來衡量的,很多介紹都對Z一筆帶過,
后面重點講一下這個Z的含義,也就是物體距離攝像機的“距離”。
視口坐標系是將Game視圖的屏幕坐標系單位化,左下角(0,0),右上角(1,1)
驗證如下:
創建一個cube,和一個相機,為相機掛上腳本CameraConvert.cs
using UnityEngine; public class CameraConvert : MonoBehaviour { public Transform target; Camera camera; void Start() { camera = GetComponent<Camera>(); Vector3 worldPos1 = target.position; Vector3 screenPos = camera.WorldToScreenPoint(worldPos1); Vector3 worldPos2 = camera.ScreenToWorldPoint(screenPos); //世界坐標系與屏幕坐標系相互轉換 Debug.Log("Screen.width" + Screen.width); Debug.Log("Screen.height" + Screen.height); Debug.Log("target world pos1 is" + worldPos1); Debug.Log("target screen Pos is " + screenPos); Debug.Log("target world pos2 is" + worldPos2); //視口坐標系(x,y范圍0-1) Debug.Log(screenPos.x / Screen.width + " " + screenPos.y / Screen.height); Debug.Log("target viewpoint Pos1 is" + camera.WorldToViewportPoint(worldPos1)); Debug.Log("target viewpoint Pos2 is " + camera.ScreenToViewportPoint(screenPos)); } }
其中 screenPos的Z坐標表示目標點據相機平面的垂直距離,這個相機平面可以這樣確定,1.與nearPlane平面平行,過相機位置點。可以通過以下代碼求得:
//計算Z的輔助平面 Plane plane1 = new Plane(transform.forward,transform.position); float distance = plane1.GetDistanceToPoint (target.position); Debug.Log ("distance:" + distance);
另,可以看下這篇博客。