原文連結:
http://blog.csdn.net/zuoyamin/article/details/8813424
- World Space(全局座標):我們在情境中添加物體(如:Cube),他們都是以全局座標顯示在情境中的。transform.position可以獲得該位置座標。
-
Screen Space(螢幕座標):以像素來定義的,以螢幕的左下角為(0,0)點,右上方為(Screen.width,Screen.height),Z的位置是以相機的世界單位來衡量的。註:滑鼠位置座標屬於螢幕座標,Input.mousePosition可以獲得該位置座標,手指觸控螢幕幕也為螢幕座標,Input.GetTouch(0).position可以獲得單個手指觸控螢幕幕座標。
-
ViewPort Space(視口座標):視口座標是標準的和相對於相機的。相機的左下角為(0,0)點,右上方為(1,1)點,Z的位置是以相機的世界單位來衡量的。(用的不多,反正我暫時沒有用到~呵呵~)
-
繪製GUI介面的座標系:這個座標系與螢幕座標系相似,不同的是該座標系以螢幕的左上方為(0,0)點,右下角為(Screen.width,Screen.height)。
-
全局座標→螢幕座標:camera.WorldToScreenPoint(transform.position);這樣可以將全局座標轉換為螢幕座標。其中camera為情境中的camera對象。
-
螢幕座標→視口座標:camera.ScreenToViewportPoint(Input.GetTouch(0).position);這樣可以將螢幕座標轉換為視口座標。其中camera為情境中的camera對象。
-
視口座標→螢幕座標:camera.ViewportToScreenPoint();
- 視口座標→全局座標:camera.ViewportToWorldPoint();
- 案例1——在滑鼠點擊的位置上繪製一張圖片出來(關於繪製GUI介面座標系與螢幕座標系之間的關係)。[csharp] view plaincopy
- using UnityEngine;
- using System.Collections;
- public class test : MonoBehaviour {
- //圖片
- public Texture img;
- //儲存滑鼠的位置座標
- private Vector2 pos;
- void OnGUI()
- {
- //滑鼠左擊,擷取當前滑鼠的位置
- if (Input.GetMouseButton(0))
- {
- pos = Input.mousePosition;
- }
- //繪製圖片
- GUI.DrawTexture(new Rect(pos.x,Screen.height - pos.y,100,100), img);
- }
- }
- 案例2——座標顯示和座標轉換(這個是觸摸方面的。如果沒有觸控螢幕,那就將那個if去掉吧!)[csharp] view plaincopy
- using UnityEngine;
- using System.Collections;
- public class test: MonoBehaviour {
- //情境的相機,拖放進來
- public Camera camera;
- //情境的物體
- private GameObject obj;
- void Start()
- {
- //初始化
- obj = GameObject.Find("Plane");
- }
- void Update ()
- {
- //有觸摸
- if (Input.touchCount > 0)
- {
- print("全局座標" + obj.transform.position);
- print("螢幕座標" + Input.GetTouch(0).position);
- print("全局座標→螢幕座標" + camera.WorldToScreenPoint(obj.transform.position));
- print("螢幕座標→視口座標" + camera.ScreenToViewportPoint(Input.GetTouch(0).position));
- print("全局座標→視口座標" + camera.WorldToViewportPoint(obj.transform.position));
- }
- }
- }