Unity_屏幕/Viewport/世界坐標的轉換


Unity_屏幕/Viewport/世界/UI坐標的轉換

參考:

  https://www.jianshu.com/p/b5b6ac9ab145 -- 世界、視口、屏幕坐標轉換
  https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html -- API

不同坐標系:

世界坐標系: World Space
  transform.position/ transform.rotation都是基於世界坐標系的
  游戲場景的原點世界坐標為(0,0,0)

觀察坐標: Eye Space
  在Game視圖中的畫面是由攝像機提供的,而基於某一個攝像機的坐標系即為觀察坐標系
  即把攝像機的位置作為原點位置

視口坐標: View Port
  針對整個游戲畫面,左下角為(0,0),右上角為(1,1)
  設計分屏功能時可以通過設置攝像機所占的視口空間來控制

屏幕坐標: Screen Space
  與游戲畫面的分辨率有關,注意是游戲屏幕畫面的分辨率
  屏幕的左下角為(0,0), 右上角為(Screen.width, Screen.height)
  獲取鼠標位置(Input.mousePosition)時的坐標即為屏幕坐標,返回的為Vector3(x,y,0)

常見方法:

// 1.屏幕轉世界坐標
Vector3 Camera.main.ScreenToWorldPoint(new Vector3(screenPos.x , screenPos.y , zInfo));
// 世界轉屏幕坐標
Vector3 Camera.main.WorldToScreenPoint(new Vector3(worldPos.x , worldPos.y , worldPos.z));
// 2.世界轉視口坐標
Vector3 Camera.main.WorldToViewportPoint();
// 視口轉世界坐標
Vector3 Camera.main.ViewportToWorldPoint(new Vector3(viewPortPos.x , viewPortPos.y , zInfo));
// 3.視口轉屏幕坐標
Vector3 Camera.main.ViewportToScreenPoint();
// 屏幕轉視口坐標
Vector3 Camera.main.ScreenToViewportPoint();

屏幕坐標與世界坐標的轉換: 
  注意: z表示的是世界坐標相對於攝像機的深度信息
    例: 世界坐標(0, 0, 1),攝像機位置(0, 0, -10)  --  WorldToScreenPoint()返回結果為(Screen.width/2, Screen.height/2, 1-(-10))

視口坐標和世界坐標的轉換也類似:
  z也表示的為深度信息(距離)

應用:

1. 有些游戲會對物體的運動范圍進行限制,防止跑出邊界,比如雷電

思路:
  用世界坐標和視口坐標的轉化
  將物體的視口坐標限制在(0,0,x)~(1,1,x)內/ 或用(0,0,x)(1,1,x)的視口坐標算出物體的世界坐標的x和y的限制(四條邊界)

注意:
  上述雷電游戲由於攝像機使用了正交投影,所以z軸數據沒有關系
  但是如果使用的是透視投影,則在不同深度下的邊界范圍會發生變化,因此需要輸入正確的z軸數據

屏幕坐標轉UI坐標:

 

方法: 將屏幕上的一點screenPoint,轉換為UI RectTransform的局部空間中的坐標

public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint);

參數詳解:
  RectTransform rect: The RectTransform to find a point inside
  Camera cam: The camera associated with the screen space position
    1. For a RectTransform in a Canvas set to Screen Space-Overlay mode, cam parameter should be null.
    2. When ScreenPointToLocalPointInRectangle is used from within an event handler that provides a PointerEventData,
      the correct camera can be obtained by using PointerEventData.enterEventData (for hover)
      or  PointerEventData.pressedEventCamera (for click)
      it will auto use the correct camera( or null) for the given event
  out Vector2 localPoint: Point in local space of the rect
  return: returns true if the plane of the RectTransform in hit, regardless of whether the point is inside the rect
    整個平面,而不是矩形內部

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM