在Unity Editor下,當選擇Camera組件后,可呈現出Camera視口區域錐體,非常方便。但是當選擇其他物體,如Cube后,就無法得知是否在Camera市口區內了,這里我找到了雨松MOMO的一篇博客《Unity3D研究院之獲取攝像機的視口區域》,他用Camera.fieldOfView和Camera.aspect算出屏幕比例,然后再得出width、height(攝像機)繪制了四邊形,非常酷,可以解決這個痛點。
我在巨人肩膀上,做了一些拓展:
自動獲得Camera的farClipPlane和nearClipPlane
void Start()
{
if (!theCamera)
{
theCamera = this.GetComponent<Camera>();
}
upperDistance = theCamera.farClipPlane;
lowerDistance = theCamera.nearClipPlane;
tx = theCamera.transform;
}
連線far和near ClipPlane
void FindLower2UpperCorners()
{
Vector3[] corners_upper = GetCorners(upperDistance);
Vector3[] corners_lower = GetCorners(lowerDistance);Debug.DrawLine(corners_lower[0], corners_upper[0], Color.blue);
Debug.DrawLine(corners_lower[1], corners_upper[1], Color.blue);
Debug.DrawLine(corners_lower[2], corners_upper[2], Color.blue);
Debug.DrawLine(corners_lower[3], corners_upper[3], Color.blue);
}
掛接這個CameraViewEx.cs腳本到Camera組件同GameObject即可, 運行時有效:
源碼下載地址:http://git.oschina.net/xifarm/VR_Mojing/
備注:
不用這個腳本,直接在Game視圖,打開Gizmos也可以看到Unity自帶的Camera視口區域錐體。