Unity3D的四種座標系詳細介紹

轉載地址:http://www.unitymanual.com/blog-1240-722.html

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界面座標系與屏幕座標系之間的關係)。

[code]phpcode:

01 using UnityEngine; 
02  
03 using System.Collections; 
04  
05 public class test : MonoBehaviour { 
06  
07 //圖片 
08  
09 public Texture img; 
10  
11 //儲存鼠標的位置座標 
12  
13 private Vector2 pos; 
14  
15 void OnGUI() 
16  
17
18  
19 //鼠標左擊,獲取當前鼠標的位置 
20  
21 if (Input.GetMouseButton(0)) 
22  
23
24  
25 pos = Input.mousePosition; 
26  
27
28  
29 //繪製圖片 
30  
31 GUI.DrawTexture(new Rect(pos.x,Screen.height - pos.y,100,100), img); 
32  
33
34  
35

案例2——座標顯示和座標轉換(這個是觸摸方面的。如果沒有觸摸屏,那就將那個if去掉吧!)

[code]phpcode:

01 using UnityEngine; 
02  
03 using System.Collections; 
04  
05 public class test: MonoBehaviour { 
06  
07 //場景的相機,拖放進來 
08  
09 public Camera camera; 
10  
11 //場景的物體 
12  
13 private GameObject obj; 
14  
15 void Start() 
16  
17
18  
19 //初始化 
20  
21 obj = GameObject.Find("Plane"); 
22  
23
24  
25 void Update () 
26  
27
28  
29 //有觸摸 
30  
31 if (Input.touchCount > 0) 
32  
33
34  
35 print("世界座標" + obj.transform.position); 
36  
37 print("屏幕座標" + Input.GetTouch(0).position); 
38  
39 print("世界座標→屏幕座標" + camera.WorldToScreenPoint(obj.transform.position)); 
40  
41 print("屏幕座標→視口座標" + camera.ScreenToViewportPoint(Input.GetTouch(0).position)); 
42  
43 print("世界座標→視口座標" + camera.WorldToViewportPoint(obj.transform.position)); 
44  
45
46  
47
48  
49

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章