天天看點

Unity(4)-坐标系統

B站學習筆記

連結:https://www.bilibili.com/video/BV12s411g7gU?p=174

Unity(4)-坐标系統

Unity坐标系

  • World Space
  • 世界(全局)坐标系:整個場景的固定坐标,原點為世界的(0,0,0)。
  • 作用:在遊戲場景中表示每個遊戲對象的位置和方向。
  • Local Space
  • 物體(局部)坐标系:每個物體獨立的坐标系,原點為模型軸心點,随物體移動或旋轉而改變。
  • 作用:表示物體間相對位置和方向。
  • Screen Space
  • 螢幕坐标系:以像素為機關,螢幕左下角為原(0,0)點,右上角為螢幕寬、高度(Screen.width,Screen.height),Z為到相機的距離。
  • 作用:表示物體在螢幕中的位置。
    Unity(4)-坐标系統
  • Viewport Space
  • 視口(錄影機)坐标系:螢幕左下角為原(0,0)點,右上角為(1,1),Z為到相機的距離。
  • 作用:表示物體在錄影機中的位置。
    Unity(4)-坐标系統

坐标系轉換

Local Space --> World Space

  • transform.forward 在世界坐标系中表示物體的正前方。
  • transform.right 在世界坐标系中表示物體的正右方。
  • transform.up 在世界坐标系中表示物體的正上方。
  • transform.TransformPoint

    轉換點,受變換元件位置、旋轉和縮放影響。

  • transform.TransformDirection

    轉換方向,受變換元件旋轉影響。

  • transform.TransformVector

    轉換向量,受變換元件旋轉和縮放影響。

World Space --> Local Space

  • transform.InverseTransformPoint

    轉換點,受變換元件位置、旋轉和縮放影響。

  • transform.InverseTransformDirection

    轉換方向,受變換元件旋轉影響。

  • transform.InverseTransformVector

    轉換向量,受變換元件旋轉和縮放影響。

World Space <—>Screen Space

  • Camera.main.WorldToScreenPoint

    将點從世界坐标系轉換到螢幕坐标系中

  • Camera.main.ScreenToWorldPoint

    将點從螢幕坐标系轉換到世界坐标系中

練習:(1)小飛機如果超過螢幕,停止運動

(2)左出右進 右出左進

Unity(4)-坐标系統
public class PlayerController : MonoBehaviour
{
    private Camera mainCamera;

    private void Start()
    {
        //重複使用的引用放在Start裡先找一次,之後直接引用自己的引用
        mainCamera = Camera.main;
    }

    void Update()
    {
        float hor = Input.GetAxis("Horizontal");
        float ver = Input.GetAxis("Vertical");
        if (hor != 0 || ver != 0)
            Movement(hor,ver);
    }

    public float moveSpeed = 10;

    private void Movement(float hor, float ver)
    {
        hor *= moveSpeed * Time.deltaTime;
        ver *= moveSpeed * Time.deltaTime;

        //判斷物體的螢幕坐标
        //世界坐标轉換為螢幕坐标
        Vector3 screenPoint = mainCamera.WorldToScreenPoint(this.transform.position);
        //限制
        //(1)如果超過螢幕,停止運動
        if (screenPoint.y>=Screen.height&&ver>0 || screenPoint.y<=0&& ver<0)
        {
            ver=0;
        }
        如果到了最左邊/到了最右邊 還想移動 
        if (screenPoint.x >= Screen.width&&hor>0 || screenPoint.x<=0&& hor<0)
        {
            hor = 0;
        }
        //(2)左出右進 右出左進
        //上進下出 下進上出
       
        if (screenPoint.y > Screen.height)
        {
            screenPoint.y = 0;
        }
        if(screenPoint.y < 0)
        {
            screenPoint.y = Screen.height;
        }
        if (screenPoint.x > Screen.width )
        {
            screenPoint.x = 0;
        }
        if (screenPoint.x < 0)
        {
            screenPoint.x = Screen.width;
        }
        this.transform.position = mainCamera.ScreenToWorldPoint(screenPoint);
        this.transform.Translate(hor, 0, ver);
    }
}

           

注意:在做上進下出左進右出時需要将螢幕坐标轉換為世界坐标才能實際改變物體的位置。