u3d之世界坐标系,屏幕坐标系,视口坐标系,如何获取物体距离摄像机的距离

世界坐标系就是unity的左手坐标系

屏幕坐标系是Game视图相机拍摄的场景坐标系,左下角(0,0),右上角(Screen.width,Screen.height),单位是像素。Z的位置是以相机的世界单位来衡量的,很多介绍都对Z一笔带过,

后面重点讲一下这个Z的含义,也就是物体距离摄像机的“距离”。

视口坐标系是将Game视图的屏幕坐标系单位化,左下角(0,0),右上角(1,1)

验证如下:

创建一个cube,和一个相机,为相机挂上脚本CameraConvert.cs

using UnityEngine;

public class CameraConvert : MonoBehaviour {
 
    public Transform target;
    Camera camera;

    void Start()
    {
        camera = GetComponent<Camera>();
        
        Vector3 worldPos1 = target.position;
        Vector3 screenPos = camera.WorldToScreenPoint(worldPos1);
        Vector3 worldPos2 = camera.ScreenToWorldPoint(screenPos);
        
        //世界坐标系与屏幕坐标系相互转换
        Debug.Log("Screen.width" + Screen.width);
        Debug.Log("Screen.height" + Screen.height);
        Debug.Log("target world pos1 is" + worldPos1);
        Debug.Log("target screen Pos is " + screenPos);
        Debug.Log("target world pos2 is" + worldPos2);
        
        //视口坐标系(x,y范围0-1)
        Debug.Log(screenPos.x / Screen.width + " " + screenPos.y / Screen.height);
        Debug.Log("target viewpoint Pos1 is" + camera.WorldToViewportPoint(worldPos1));
        Debug.Log("target viewpoint Pos2 is " + camera.ScreenToViewportPoint(screenPos));
    }
 
}

其中 screenPos的Z坐标表示目标点据相机平面的垂直距离,这个相机平面可以这样确定,1.与nearPlane平面平行,过相机位置点。可以通过以下代码求得:

//计算Z的辅助平面
Plane plane1 = new Plane(transform.forward,transform.position);
		
float distance = plane1.GetDistanceToPoint (target.position);
Debug.Log ("distance:" + distance); 

  

另,可以看下这篇博客

posted @ 2017-06-05 16:42  lipper_p  Views(6195)  Comments(1Edit  收藏  举报