Unity3D之座標系的轉換

一, Unity中的常用座標系

1⃣️,世界座標系 (左手定則)

        this.transform.Position

2⃣️,本地座標系(左手定則)

        this.transform.LocalPosition

3⃣️,屏幕座標系

            1,左下角爲原點(0,0)

            2,右上角爲 (Screen.Width,Screen.Hight

            3,Z的位置是以相機的世界單位來衡量//及物體離相機遠近

         4,和屏幕分辨率有關

         5,鼠標位置座標屬於屏幕座標,Input.mousePosition可以獲得鼠標座標,當用Input.MousePosition獲取鼠標位置的時候,他的Z軸值一直爲0

                    public Vector3 MyScreenToWorld( Vector3 mousePos, Transform targetTransform ){

                                Vector3 dir = targetTransform.position - Camera.main.transform.position;

                                //計算投影

                                Vector3 normalDir = Vector3.Project( dir, Camera.main.transform.forward );

                                //物體離相機遠近 (normalDir.magnitude

                                Vector3 worldPos = Camera.main.ScreenToWorldPoint( new Vector3(  mousePos.x , mousePos.y, normalDir.magnitude) );

                                return worldPos;

                    }

         6,手指觸摸屏也爲屏幕座標,Input.GetTouch(0).position可以獲得單個手指的手機屏幕座標

4⃣️,視口座標系

            1,左下角爲原點(0,0)

            2,右上角爲(1,1)

二,座標系轉換

        1⃣️,世界座標和本地座標轉換

                1,本地轉世界 : this.transform.TransformPoint(0,0,0);

                2,世界轉本地: this.transform.InverseTransformPoint(0,0,0);

        2⃣️,世界座標和屏幕座標轉換

                1, 世界轉屏幕:Camera.main.WorldToScreenPoint( vector3 );

                2,   屏幕轉世界:Camera.main.ScreenToWorldPoint(vector3);

        3⃣️,世界座標和視口座標轉換

                1,世界轉視口:Camera.main.WorldToViewportPoint(0,0,0);               

                2,  視口轉世界:Camera.main.ViewportToWorldPoint(0,0,0);

        4⃣️,屏幕座標和視口座標轉換

                1,屏幕轉視口:Camera.main.ScreenToViewportPoint(0,0,0);

                2,  視口轉屏幕:Camera.main.ViewportToScreenPoint(0,0,0);


  if (Input.GetMouseButtonDown(0))

        {

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);   // 從鼠標位置發送射線

            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 100, 1 << LayerMask.NameToLayer("Plane")))

            {

                Debug.Log(hit.collider.name);

            }

        }



   if (Input.GetMouseButtonDown(0))

        {

            Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));    // 從屏幕中央發送射線

            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 100, 1 << LayerMask.NameToLayer("Plane")))

            {

                Debug.Log(hit.collider.name);

            }

        }


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