Unity坐标转换

世界坐标转换本地坐标

public Transform ObjectPos;

public void   CdPos()

{

Transform  parent=ObjectorPos;

vector3 local=parent.InverseTransformPoint(parent.transform);

vector3 pos=parent.TransformPoint(local);

//这里的pos就是本地左标,也就是Inspector面板上的坐标

}

//世界坐标转屏幕坐标 

Vector3 screenpos =  camera,main.WorldToScreenPoint( ObjectPos.position);

//屏幕转世界

Vector3 worldPos = canvas.main.ScreenToWorldPoint(new Vector3(screenpos.x, screenpos.y, uictrl.uiCanvas.transform.position.z));

//这里都是在主相机下的左边转换

贴出一段我工作中不同Canvas下不同相机坐标转换物体移动, 一个canvas的相机是正交,一个是透视,坐标转换

              var correctPos = uiMjSort.transform;

                var uictrl = UIControl.Instance;

                Vector3 screenpos = uictrl.game_Camera.WorldToScreenPoint(correctPos.position);

                Vector3 worldPos = uictrl.ui_Camera.ScreenToWorldPoint(new Vector3(screenpos.x, screenpos.y, uictrl.uiCanvas.transform.position.z));

                correctPos.SetParent(uictrl.uiCanvas.transform);

                correctPos.position = worldPos;

                correctPos.localScale = new Vector3(uictrl.GetScaleCanera(uictrl.game_Camera.transform.position.z), uictrl.GetScaleCanera(uictrl.game_Camera.transform.position.z), uictrl.GetScaleCanera(uictrl.game_Camera.transform.position.z));坐标转换后需要修正缩放值

                var mjBox = uictrl.uiGame.MahjongBox;


                correctPos.DOScale(new Vector3(0.7f, 0.65f, 0.65f), 0.7f);//dotween缩放

                correctPos.DOMove(mjBox.transform.position, 0.7f).OnComplete(delegate { correctPos.SetParent(mjBox.transform);//移动,效果就是一边移动一边缩放

ps:我的分辨率是720x1280;


///

    ///  根据缩放求相机距离

    ///

    ///

    ///

    private float GetDistanceCamera(float scale)

    {

        return -(1280f / scale * 0.5f) / Mathf.Tan(Mathf.Deg2Rad * game_Camera.fieldOfView * 0.5f);

    }

    ///

    /// 根据距离求缩放值

    ///

    ///

    ///

    public float GetScaleCanera(float distance)

    {

        float num = distance * Mathf.Tan(Mathf.Deg2Rad * game_Camera.fieldOfView * 0.5f);

        float scl = 640f / num;

        return Mathf.Abs(640f / num);

    }

你可能感兴趣的:(Unity坐标转换)