-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFOVTest.cs
73 lines (54 loc) · 2.49 KB
/
FOVTest.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
using UnityEngine;
public class FOVTest : MonoBehaviour {
public Transform Target;
[Space]
public float AngleX = 45;
public float AngleY = 25;
[Space, Header("Debug & Visuals")]
public bool DrawFOV = true;
public bool AlsoCheckOutside = false;
public int Divisions = 25;
public int PlaneDistance = 10;
void Awake() {
DrawFOV = false;
}
void Update() {
if (IsWithinScope(Target.position)) { Debug.DrawLine(transform.position, Target.position, Color.green); }
else { Debug.DrawLine(transform.position, Target.position, Color.red); }
Debug.DrawRay(transform.position, transform.forward * 100, Color.yellow);
}
public bool IsWithinScope(Vector3 objectPosition) {
var directionToObject = objectPosition - transform.position;
var planeDistance = Vector3.Dot(transform.forward, directionToObject);
var planeHeight = planeDistance * 2 * Mathf.Tan(AngleY * Mathf.Deg2Rad);
var planeWidth = planeHeight * AngleX / AngleY;
var objectDistanceFromPlanesCenter = new Vector2();
objectDistanceFromPlanesCenter.x = Vector3.Dot(directionToObject, transform.right);
objectDistanceFromPlanesCenter.y = Vector3.Dot(directionToObject, transform.up);
bool passesXTest = Mathf.Abs(objectDistanceFromPlanesCenter.x) <= planeWidth / 2;
bool passesYTest = Mathf.Abs(objectDistanceFromPlanesCenter.y) <= planeHeight / 2;
return passesXTest && passesYTest;
}
// Visual representation of the Field of View
void OnDrawGizmos() {
if (!DrawFOV || Divisions <= 0 || PlaneDistance <= 0 || AngleX <= 0 || AngleY <= 0 || AngleY >= 90) { return; }
// Define the plane
Vector3 planeCenter = transform.position + PlaneDistance * transform.forward;
var planeHeight = PlaneDistance * 2 * Mathf.Tan(AngleY * Mathf.Deg2Rad);
var planeWidth = planeHeight * AngleX / AngleY;
var iterationMulti = 0.5f;
if (AlsoCheckOutside) { iterationMulti *= 4; }
// Divide the plane and draw rays towards it
for (float x = -planeWidth * iterationMulti; x < planeWidth * iterationMulti; x += planeWidth / Divisions) {
for (float y = -planeHeight* iterationMulti; y < planeHeight* iterationMulti; y += planeHeight / Divisions) {
var positionOnPlane = planeCenter;
positionOnPlane += x * transform.right;
positionOnPlane += y * transform.up;
// Make up for floating point errors
positionOnPlane += 0.000001f * transform.forward;
Gizmos.color = IsWithinScope(positionOnPlane) ? new Color(0, 1, 0, 0.1f) : new Color(1, 0, 0, 0.005f);
Gizmos.DrawLine(transform.position, positionOnPlane);
}
}
}
}