1. 程式人生 > >螢幕座標系和視口座標系

螢幕座標系和視口座標系

一.螢幕座標系
1.螢幕座標系: 手機螢幕或者電腦螢幕的一個座標系。
2.螢幕座標是以畫素來定義的, 螢幕左下角為原點(0,0), 右上角為(Screen.width,Screen.height), width是螢幕的寬度, height是螢幕的高度, Z值是攝像機世界座標取反,並且以相機的世界單位來衡量的。
3.螢幕座標和相機之間滿足: Screen.width = Camera.main.pixelWidth和Screen.height = Camera.main.pixelHeight這兩個條件。
4.滑鼠的位置座標屬於螢幕座標。通過Input.mousePosition獲取滑鼠的螢幕座標。
二.建立工程

1.建立一個遊戲工程, 命名為ScreenViewPort

2.在Project檢視中建立3個資料夾, Scene資料夾、Resources資料夾和Script資料夾

3.將當前場景儲存為GameScene

4.建立ScreenPosition遊戲指令碼


5.在Hierarchy檢視中建立一個空的GameObject, 命名為GameManager,並把ScreenPosition繫結在該物件上

6.更改螢幕解析度為480 * 800

7.編寫程式碼

using UnityEngine;

public class ScreenPosition : MonoBehaviour
{
	void Update () 
	{
		if(Input.GetMouseButtonDown(0))
		{
			Debug.Log ("螢幕座標:" + Input.mousePosition);
		}
	}
}

8.執行點選螢幕列印

螢幕座標:(9.0, 33.0, 0.0)

螢幕座標:(458.0, 22.0, 0.0)

螢幕座標:(228.0, 410.0, 0.0)

螢幕座標:(458.0, 795.0, 0.0)

三.視口座標系

1.攝像機的前面有一個長方形的小框子, 那個即為視口。


2.視口座標是標準化後的螢幕座標。視口座標是以0到1間的數字來表示的, 它的範圍是以左下角為(0,0), 右上角為(1,1)定義的這樣一個矩形。視口座標是一個3D座標, Z軸是以相機的世界單位來衡量的。通過對比可以發現視口座標和螢幕座標特別的相似。

3.攝像機視口比例:public float aspect{get;set;},此屬性用於獲取或設定Camera視口的寬高比例值。

4.void ResetAspect();恢復長寬比為螢幕的長寬比。

5.程式碼

using UnityEngine;

public class CameraAspect : MonoBehaviour
{
	void Start () 
	{
		Debug.Log ("預設寬高比例:" + Camera.main.aspect);
	}

	void OnGUI () 
	{
		if(GUILayout.Button("攝像機寬高比例為1"))
		{
			Camera.main.ResetAspect ();
			Camera.main.aspect = 1;
		}

		if(GUILayout.Button("攝像機寬高比例為2"))
		{
			Camera.main.ResetAspect ();
			Camera.main.aspect = 2;
		}
	}
}

四.螢幕座標和視口座標的轉換

1.從視口空間到螢幕空間的變換位置: Vector3 ViewportToScreenPoint(Vector3 position);

2.從螢幕空間到視窗空間的變換位置: Vector3 ScreenToViewportPoint(Vector3 position);

3.程式碼

using UnityEngine;

public class ScreenViewPortPosition : MonoBehaviour 
{
	void Start()
	{
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(0,0,0),"+Camera.main.ViewportToScreenPoint(new Vector3(0,0,0))+"]");
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(0.5,0,0),"+Camera.main.ViewportToScreenPoint(new Vector3(0.5f,0,0))+"]");
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(0,0.5,0),"+Camera.main.ViewportToScreenPoint(new Vector3(0,0.5f,0))+"]");
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(0.5,0.5,0),"+Camera.main.ViewportToScreenPoint(new Vector3(0.5f,0.5f,0))+"]");
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(1,0,0),"+Camera.main.ViewportToScreenPoint(new Vector3(1,0,0))+"]");
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(0,1,0),"+Camera.main.ViewportToScreenPoint(new Vector3(0,1,0))+"]");
		Debug.Log ("攝像機視口座標轉換成螢幕座標[(1,1,0),"+Camera.main.ViewportToScreenPoint(new Vector3(1,1,0))+"]");
	}

	void Update () 
	{
		if(Input.GetMouseButtonDown(0))
		{
			Debug.Log ("攝像機螢幕座標轉換成視口座標:["+Input.mousePosition+","+Camera.main.ScreenToViewportPoint(Input.mousePosition)+"]");
		}
	}
}