轉載地址: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:
03 |
using System.Collections; |
05 |
public class test : MonoBehaviour { |
21 |
if (Input.GetMouseButton(0)) |
25 |
pos = Input.mousePosition; |
31 |
GUI.DrawTexture( new Rect(pos.x,Screen.height - pos.y,100,100), img); |
案例2——座標顯示和座標轉換(這個是觸摸方面的。如果沒有觸摸屏,那就將那個if去掉吧!)
[code]phpcode:
03 |
using System.Collections; |
05 |
public class test: MonoBehaviour { |
13 |
private GameObject obj; |
21 |
obj = GameObject.Find( "Plane" ); |
31 |
if (Input.touchCount > 0) |
35 |
print( "世界座標" + obj.transform.position); |
37 |
print( "屏幕座標" + Input.GetTouch(0).position); |
39 |
print( "世界座標→屏幕座標" + camera.WorldToScreenPoint(obj.transform.position)); |
41 |
print( "屏幕座標→視口座標" + camera.ScreenToViewportPoint(Input.GetTouch(0).position)); |
43 |
print( "世界座標→視口座標" + camera.WorldToViewportPoint(obj.transform.position)); |