Unity3D研究院之获取摄像机的视口区域
生活随笔
收集整理的這篇文章主要介紹了
Unity3D研究院之获取摄像机的视口区域
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在網上看了momo的文章,在這把代碼加入些注釋,也便于自己理解記憶。原理很簡單,就是根據攝像機的參數計算距離攝像機某一距離的攝像機窗口四個position。
using UnityEngine;
using System.Collections;public class CameraView : MonoBehaviour {private Camera theCamera;//距離攝像機8.5米 用黃色表示public float upperDistance = 8.5f;//距離攝像機12米 用紅色表示public float lowerDistance = 12.0f;private Transform tx;void Start (){if ( !theCamera ){theCamera = Camera.main;}tx = theCamera.transform;}void Update (){FindUpperCorners();FindLowerCorners();}void FindUpperCorners (){Vector3[] corners = GetCorners( upperDistance );// for debuggingDebug.DrawLine( corners[0], corners[1], Color.yellow ); // UpperLeft -> UpperRight Debug.DrawLine( corners[1], corners[3], Color.yellow ); // UpperRight -> LowerRightDebug.DrawLine( corners[3], corners[2], Color.yellow ); // LowerRight -> LowerLeftDebug.DrawLine( corners[2], corners[0], Color.yellow ); // LowerLeft -> UpperLeft}void FindLowerCorners (){Vector3[] corners = GetCorners( lowerDistance );// for debuggingDebug.DrawLine( corners[0], corners[1], Color.red );Debug.DrawLine( corners[1], corners[3], Color.red );Debug.DrawLine( corners[3], corners[2], Color.red );Debug.DrawLine( corners[2], corners[0], Color.red );}Vector3[] GetCorners ( float distance ){Vector3[] corners = new Vector3[ 4 ];float halfFOV = ( theCamera.fieldOfView * 0.5f ) * Mathf.Deg2Rad; //相機的垂直視野的float aspect = theCamera.aspect; //寬高比float height = distance * Mathf.Tan( halfFOV );//tan求出所求位置相機的高度float width = height * aspect; <span style="font-family: Arial, Helvetica, sans-serif;">//根據高度和aspect求出所求位置相機的寬度// UpperLeftcorners[ 0 ] = tx.position - ( tx.right * width );corners[ 0 ] += tx.up * height;corners[ 0 ] += tx.forward * distance;// UpperRightcorners[ 1 ] = tx.position + ( tx.right * width );corners[ 1 ] += tx.up * height;corners[ 1 ] += tx.forward * distance;// LowerLeftcorners[ 2 ] = tx.position - ( tx.right * width );corners[ 2 ] -= tx.up * height;corners[ 2 ] += tx.forward * distance;// LowerRightcorners[ 3 ] = tx.position + ( tx.right * width );corners[ 3 ] -= tx.up * height;corners[ 3 ] += tx.forward * distance;return corners;}
}
總結
以上是生活随笔為你收集整理的Unity3D研究院之获取摄像机的视口区域的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue3 兄弟组件传参mitt
- 下一篇: Unity中date相关问题