-
Notifications
You must be signed in to change notification settings - Fork 0
/
FieldOfView.cs
353 lines (258 loc) · 12.6 KB
/
FieldOfView.cs
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FieldOfView : MonoBehaviour {
[Header("Field of View Settings")]
[SerializeField, Tooltip("Radius or max distance the 'player' can see")] private float viewRadius = 50f;
[SerializeField, Range(0, 360), Tooltip("Wideness of the field of view")] private float viewAngle = 90f;
[Header("Peripheral Vision Settings")]
[SerializeField, Tooltip("Should the player have a peripheral vision?")] public bool hasPeripheralVision = false;
[SerializeField, Tooltip("Radius or max distance the 'player' can see with his peripheral vision.")] private float viewRadiusPeripheralVision = 10f;
[Header("Edge Resolving Settings")]
[SerializeField, Tooltip("Iterations of the edge resolving algorithm (higher = more precise but also more costly)")] private int edgeResolveIterations = 1;
[SerializeField] private float edgeDstThreshold;
[Header("General Settings")]
[SerializeField, Range(0, 1), Tooltip("Delay between field of view updates")] private float delayBetweenFOVUpdates = 0.2f;
[Header("Layermask Settings")]
[SerializeField, Tooltip("Objects that are effected when entering/exiting the fov. These MUST IMPLEMENT the IHideable interface")] private LayerMask targetMask;
[SerializeField, Tooltip("Objects that block the field of view")] private LayerMask obstacleMask;
[Header("Visualization Settings")]
[SerializeField, Tooltip("Should the field of view be visualized?")] public bool visualizeFieldOfView = true;
[SerializeField, Tooltip("Affects the ammount of rays casted out when recalculating the fov. Raycast count = viewAngle * meshResolution")] private float meshResolution = 10;
[SerializeField, Tooltip("Affects the ammount of rays casted out when recalculating the fov. Raycast count = viewAngle * meshResolution")] private int meshResolutionEdge = 10;
[SerializeField, Tooltip("Affects the ammount of rays casted out when recalculating the fov of the players peripheral vision. Higher values are more costly! Raycast count (for the area behind the player only) = meshResolutionPeripheralVision")] private int meshResolutionPeripheralVision = 10;
[SerializeField, Tooltip("Mesh Filter component that holds the generated mesh when drawing the field of view")] private MeshFilter viewMeshFilter;
private Mesh viewMesh;
public bool UseSaver = false;
//variable is used in the DrawFieldOfView method (storing it here it way more efficient - GC.collect...)
private List<Vector3> viewPoints = new List<Vector3>();
private void Start() {
viewMesh = new Mesh();
viewMesh.name = "View Mesh";
viewMeshFilter.mesh = viewMesh;
}
void OnEnable() {
StartCoroutine("FindTargetsWithDelay", delayBetweenFOVUpdates);
}
private void LateUpdate() {
if (visualizeFieldOfView) {
viewMeshFilter.mesh = viewMesh;
DrawFieldOfView();
} else {
viewMeshFilter.mesh = null;
}
}
/// <summary>
/// Draw the field of view.
/// </summary>
bool Test1(float angle ,ViewCastInfo oldViewCast ){
Vector3 dir = DirFromAngle(angle, true);
return (oldViewCast.Collider.GetComponent<Renderer>().bounds.Contains (transform.position + (dir * Vector3.Distance (transform.position, oldViewCast.Collider.transform.GetComponent<Renderer>().bounds.center))));
}
bool Test2(ViewCastInfo oldViewCast , ViewCastInfo newViewCast){
return (oldViewCast.Collider == newViewCast.Collider && (Vector3.Distance (newViewCast.point, oldViewCast.Collider.bounds.center) > Vector3.Distance (oldViewCast.point, newViewCast.point)));
}
float Angle( int i){
return transform.eulerAngles.y - viewAngle / 2 + (viewAngle / Mathf.RoundToInt(viewAngle * meshResolution)) * i;
}
void DrawFieldOfView() {
viewPoints.Clear();
ViewCastInfo oldViewCast = new ViewCastInfo();
/* Calculate normal field of view */
for (int i = 0; i <= Mathf.RoundToInt(viewAngle * meshResolution); i++) {
if (i > 0 && UseSaver && oldViewCast.Collider != null && Test1(Angle(i) ,oldViewCast) ) {
i = i + 5;
}
ViewCastInfo newViewCast = ViewCast(transform.eulerAngles.y - viewAngle / 2 + (viewAngle / Mathf.RoundToInt(viewAngle * meshResolution)) * i, viewRadius ,Color.blue);
if (i > 0 && UseSaver) {
if (oldViewCast.Collider != null && newViewCast.Collider != null) {
if (Test2(oldViewCast,newViewCast)) {
viewPoints.Add (newViewCast.point);
oldViewCast = newViewCast;
continue;
}
}
}
if (i > 0) {
if (oldViewCast.hit != newViewCast.hit || (oldViewCast.hit && newViewCast.hit && Mathf.Abs(oldViewCast.distance - newViewCast.distance) > edgeDstThreshold) ) {
EdgeInfo edge = FindEdge(oldViewCast, newViewCast, viewRadius);
if (edge.pointA != Vector3.zero) {
viewPoints.Add(edge.pointA);
}
if (edge.pointB != Vector3.zero) {
viewPoints.Add(edge.pointB);
}
}
}
viewPoints.Add(newViewCast.point);
oldViewCast = newViewCast;
}
/* Calculate peripheral vision */
if (hasPeripheralVision && viewAngle < 360) {
//cast out shorter rays around the player to make sure he is always able to see a bit in all directions
for (int i = 0; i < meshResolutionPeripheralVision + 1; i++) {
ViewCastInfo newViewCast = ViewCast(transform.eulerAngles.y + viewAngle / 2 + i * (360 - viewAngle) / meshResolutionPeripheralVision, viewRadiusPeripheralVision ,Color.green);
//viewPoints.Add(newViewCast.point);
if (i > 0) {
if (oldViewCast.hit != newViewCast.hit || (oldViewCast.hit && newViewCast.hit && Mathf.Abs(oldViewCast.distance - newViewCast.distance) > edgeDstThreshold)) {
EdgeInfo edge = FindEdge(oldViewCast, newViewCast, viewRadiusPeripheralVision);
if (edge.pointA != Vector3.zero) {
viewPoints.Add(edge.pointA);
}
if (edge.pointB != Vector3.zero) {
viewPoints.Add(edge.pointB);
}
}
}
viewPoints.Add(newViewCast.point);
oldViewCast = newViewCast;
}
}
/* Draw mesh */
int vertexCount = viewPoints.Count + 1;
Vector3[] vertices = new Vector3[vertexCount];
int[] triangles = new int[(vertexCount - 2) * 3];
vertices[0] = Vector3.zero;
for (int i = 0; i < vertexCount - 1; i++) {
vertices[i + 1] = transform.InverseTransformPoint(viewPoints[i]);
if (i < vertexCount - 2) {
triangles[i * 3] = 0;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = i + 2;
}
}
viewMesh.Clear();
viewMesh.vertices = vertices;
viewMesh.triangles = triangles;
viewMesh.RecalculateNormals();
}
/// <summary>
/// Cast out a ray at a given angle and return a ViewCastInfo struct as a result.
/// </summary>
/// <param name="globalAngle"></param>
/// <returns></returns>
ViewCastInfo ViewCast(float globalAngle, float viewRadius , Color color) {
Vector3 dir = DirFromAngle(globalAngle, true);
RaycastHit hit;
Physics.autoSyncTransforms = false;
Debug.DrawRay(transform.position, dir * viewRadius,color);
if (Physics.Raycast(transform.position, dir, out hit, viewRadius, obstacleMask)) {
Physics.autoSyncTransforms = true;
return new ViewCastInfo(true, hit.point, hit.distance, globalAngle,hit.collider);
} else {
Physics.autoSyncTransforms = true;
return new ViewCastInfo(false, transform.position + dir * viewRadius, viewRadius, globalAngle,hit.collider);
}
}
/// <summary>
/// Finds the edge of a collider
/// </summary>
/// <param name="minViewCast"></param>
/// <param name="maxViewCast"></param>
/// <returns></returns>
EdgeInfo FindEdge(ViewCastInfo minViewCast, ViewCastInfo maxViewCast, float viewRadius) {
float minAngle = minViewCast.angle;
float maxAngle = maxViewCast.angle;
Vector3 minPoint = Vector3.zero;
Vector3 maxPoint = Vector3.zero;
for (int i = 0; i < edgeResolveIterations; i++) {
float angle = (minAngle + maxAngle) / 2;
ViewCastInfo newViewCast = ViewCast(angle, viewRadius,Color.yellow);
bool edgeDstThresholdExceeded = Mathf.Abs(minViewCast.distance - newViewCast.distance) > edgeDstThreshold;
if (newViewCast.hit == minViewCast.hit && !edgeDstThresholdExceeded) {
minAngle = angle;
minPoint = newViewCast.point;
} else {
maxAngle = angle;
maxPoint = newViewCast.point;
}
}
return new EdgeInfo(minPoint, maxPoint);
}
/// <summary>
/// Run the find visible targets method every x seconds/ms
/// </summary>
/// <param name="delay"></param>
/// <returns></returns>
IEnumerator FindTargetsWithDelay(float delay) {
while (true) {
FindVisibleTargets();
yield return new WaitForSeconds(delay);
}
}
/// <summary>
/// Finds all visible targets and adds them to the visibleTargets list.
/// </summary>
void FindVisibleTargets() {
Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, viewRadius, targetMask);
Physics.autoSyncTransforms = false;
/* check normal field of view */
for (int i = 0; i < targetsInViewRadius.Length; i++) {
Transform target = targetsInViewRadius[i].transform;
bool isInFOV = false;
//check if hideable should be hidden or not
Vector3 dirToTarget = (target.position - transform.position).normalized;
if (Vector3.Angle(transform.forward, dirToTarget) < viewAngle / 2) {
float dstToTarget = Vector3.Distance(transform.position, target.position);
if (!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask)) {
isInFOV = true;
}
} else if (hasPeripheralVision) {
float dstToTarget = Vector3.Distance(transform.position, target.position);
// here we have to check the distance to the target since the peripheral vision may have a different radius than the normal field of view
if (dstToTarget < viewRadiusPeripheralVision && !Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask)) {
isInFOV = true;
}
}
//apply effect to IHideable
IHideable hideable = target.GetComponent<IHideable>();
if (hideable != null) {
if (isInFOV) {
target.GetComponent<IHideable>().OnFOVEnter();
} else {
target.GetComponent<IHideable>().OnFOVLeave();
}
}
}
Physics.autoSyncTransforms = true;
}
/// <summary>
/// Convert an angle to a direction vector.
/// </summary>
/// <param name="angleInDegrees"></param>
/// <returns></returns>
public Vector3 DirFromAngle(float angleInDegrees, bool IsAngleGlobal) {
if (!IsAngleGlobal) {
angleInDegrees += transform.eulerAngles.y;
}
return new Vector3(Mathf.Sin(angleInDegrees * Mathf.Deg2Rad), 0, Mathf.Cos(angleInDegrees * Mathf.Deg2Rad));
}
}
/// <summary>
/// Struct used to store information about a view raycast
/// </summary>
public struct ViewCastInfo {
public bool hit;
public Vector3 point;
public float distance;
public float angle;
public Collider Collider;
public ViewCastInfo(bool hit, Vector3 point, float distance, float angle, Collider Collider ) {
this.hit = hit;
this.point = point;
this.distance = distance;
this.angle = angle;
this.Collider = Collider;
}
}
/// <summary>
/// Stcuct that hold information about an edge
/// </summary>
public struct EdgeInfo {
public Vector3 pointA;
public Vector3 pointB;
public EdgeInfo(Vector3 pointA, Vector3 pointB) {
this.pointA = pointA;
this.pointB = pointB;
}
}