攝像機分爲兩種,一種是正交攝像機還有一種是透視攝像機。正交攝像機不管遠近它的視口範圍永遠是固定的,可是透視攝像機是由原點向外擴散性發射,也就是距離越遠它的視口區域也就越大。那麼咱們如何獲取距離攝像機任意距離的視口區域呢?以下圖所示,分別用紅色和黃色兩種顏色將計算出來的視口區域標記了出來。html
下面上代碼,把以下腳本掛在攝像機出直接運行遊戲便可看到。算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
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;
}
}
|
這個腳本是我在逛國外網站無心間發現的,我這裏翻譯成了C#語言。http://answers.unity3d.com/questions/509466/scale-box-collider-to-camera-view-1.html?sort=oldestide
咱們能夠根據文章裏的算法計算出視口3D的座標點,有了座標信息那麼想幹什麼都好乾了,呵呵。網站