Unity3D研究院之获取摄像机的视口区域

本文介绍了一个Unity脚本,该脚本用于计算并可视化摄像机在不同距离下的视锥角范围。通过绘制线条表示上下左右四个角点的位置,帮助开发者直观理解不同距离处的视野范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 debugging
		Debug.DrawLine( corners[0], corners[1], Color.yellow ); // UpperLeft -> UpperRight
		Debug.DrawLine( corners[1], corners[3], Color.yellow ); // UpperRight -> LowerRight
		Debug.DrawLine( corners[3], corners[2], Color.yellow ); // LowerRight -> LowerLeft
		Debug.DrawLine( corners[2], corners[0], Color.yellow ); // LowerLeft -> UpperLeft
	}
	
	
	void  FindLowerCorners (){
		Vector3[] corners = GetCorners( lowerDistance );
		
		// for debugging
		Debug.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 );
		float width = height * aspect;
		
		// UpperLeft
		corners[ 0 ] = tx.position - ( tx.right * width );
		corners[ 0 ] += tx.up * height;
		corners[ 0 ] += tx.forward * distance;
		
		// UpperRight
		corners[ 1 ] = tx.position + ( tx.right * width );
		corners[ 1 ] += tx.up * height;
		corners[ 1 ] += tx.forward * distance;
		
		// LowerLeft
		corners[ 2 ] = tx.position - ( tx.right * width );
		corners[ 2 ] -= tx.up * height;
		corners[ 2 ] += tx.forward * distance;
		
		// LowerRight
		corners[ 3 ] = tx.position + ( tx.right * width );
		corners[ 3 ] -= tx.up * height;
		corners[ 3 ] += tx.forward * distance;
		
		return corners;
	}
}


http://www.xuanyusong.com/archives/3036


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值