https://li-kang.gitbooks.io/unity-concise-course/content/Summary/coordinate.html
座標系
在3D數學座標系中,提到了以下3種座標系。 全局座標系:以大家公認的原點和軸向建立的座標系。 物體座標系:以物體位置和自身軸向建立的座標系。 慣性座標系:以物體位置和全局座標系軸向建立的座標系。 全局座標系 Unity的Scene面板中(0,0,0)的位置就是全局座標系的原點。 右上方示意圖指明了全局座標系的軸向。
transform.position; // 全局座標系中物體的位置transform.forward; // 全局座標系中物體的前方
物體座標系 選擇一個物體時,檢視面板Transform下的Position、Rotation、Scale指的是它在父物體座標系中的位置、旋轉、縮放。 當一個物體沒有指定父物體時,它的父物體就是世界。也就是說這時檢視面板Transform下的Position正好是它在全局座標系中的位置。 Unity引擎中物體儲存的都是相對於父物體座標系中的資料,所以當父物體變化(移動、旋轉、縮放)時,子物體會同步變化。
[截圖Transfrom面板]
transform.localPosition; // 在父物體座標系中的位置transform.localRotation; // 在父物體座標系中的旋轉transform.localScale; // 在父物體座標系中的縮放
螢幕座標系 螢幕座標系是2維的。 螢幕座標系是以螢幕左下角為(0,0), 右上方 (camera.pixelWidth, camera.pixelHeight)建立的座標系。
Input.mousePosition; // 擷取滑鼠在螢幕座標系中的位置
視口座標系 視口座標系也是用來反應螢幕中位置的。 視口座標系使用的是螢幕寬度和高度的百分比,其左下角(0,0),右上方 (1,1)。 視口座標系適合用來在不同大小的螢幕間做適配。
GUI座標系 專門用與GUI的座標系。 與螢幕座標是上下顛倒的。 其左上方(0,0), 右下角 (Screen.width, Screen.hight)
座標系的轉換 GUI\螢幕間的轉化
// 螢幕座標與GUI座標間的轉化方面是一樣的Vector2 TransformScreenAndGui(Vector2 point) { Vector2 result; // x軸不變 result.x = point.x; // y軸為螢幕高度減去原y座標 result.y = Screen.hight - point.y; return result;} 螢幕\視口\世界間的轉化
// 螢幕轉視口Camera.main.ScreenToViewportPoint(Input.mousePosition); // 視口轉螢幕Camera.main.ViewportToScreenPoint(new Vector3(0.25F, 0.1F, 0));// 螢幕轉世界// 轉化後z軸不變// 如果輸入的是Vector2,轉化後z軸大小為camera的z軸值camera.ScreenToWorldPoint(Input.mousePosition);// 世界轉螢幕camera.WorldToScreenPoint(target.transform.position);// 視口轉世界camera.ViewportToWorldPoint(new Vector3(1, 1, camera.nearClipPlane));// 世界轉視口camera.WorldToViewportPoint(target.transform.position);
物體\世界間的轉化
// 物體轉全局座標transform.TransformPoint(3, 4, 5); // 世界轉物體座標transform.InverseTransformPoint(3, 4, 5);// 物體座標系中的方向轉到全局座標方向transform.TransformDirection(Vector3.forward);// 全局座標系中的方向轉到物體座標方向transform.InverseTransformDirection(Vector3.forward);
運用舉例
// 確定目標在螢幕的左邊還是右邊using UnityEngine;using System.Collections;public class ExampleClass : MonoBehaviour { public Transform target; Camera camera; void Start() { camera = GetComponent<Camera>(); } void Update() { Vector3 viewPos = camera.WorldToViewportPoint(target.position); if (viewPos.x > 0.5F) print("target is on the right side!"); else print("target is on the left side!"); }}