Unity 屏幕坐标转世界坐标 && 世界坐标转屏幕坐标

一.屏幕转世界

public Transform target;//目标

    public Vector3 MyScreenToworld(Vector3 mousepos, Transform targetTransform)

    {

       //先计算相机到目标的向量

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

       //计算投影

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

       //计算是节点,需要知道处置屏幕的投影距离

       Vector3 worldpos = Camera.main.ScreenToWorldPoint(new Vector3(mousepos.x, mousepos.y, normardir.magnitude));

       return worldpos;

    }

    void Update () {

        if (Input.GetMouseButtonDown(0))

        {

           print(Input.mousePosition);

           Vector3 pos= MyScreenToworld(Input.mousePosition, target);

           print(pos);

       }

}

二. 世界转屏幕

Camera.main.WorldToScreenPoint()

猜你喜欢

转载自blog.csdn.net/h_ppap/article/details/121213654