-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSensors.cs
More file actions
250 lines (197 loc) · 7.25 KB
/
Sensors.cs
File metadata and controls
250 lines (197 loc) · 7.25 KB
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
using System.Collections.Generic;
using UnityEngine;
// Hit handling on line 178
// Implement your own hit handling logic there (interfaces, etc)
public class Sensors : MonoBehaviour
{
[Header("Options")]
[Header("Experiment with these settings to find out what works the best")]
[Tooltip("Raycast every N FixedUpdate iteration frame (1 = default) (Higher = more performant but raycasting is less frequent and thus less accurate) Increasing this can cause slightly inconsistent results but it shouldn't matter too much")]
[Range(1, 8)]
public int raycastRate = 1;
[Tooltip("How many sensor points should there be along the start and end point (Higher = less performant but more accurate)")]
public int sensorCount = 3;
public bool playOnStart = true;
[Space(8f)]
[Header("Raycast methods")]
public bool horizontalRaycasts = true;
public bool verticalRaycasts = true;
public bool intersectionRaycastsTop = true;
public bool intersectionRaycastsBottom = true;
[Header("Hit handling options")]
[Tooltip("Saves resources by stopping raycasting instantly after the first hit")]
public bool stopAfterFirstHit = false;
[Header("References")]
public Transform startPoint;
public Transform endPoint;
public Transform target;
[Header("Debug")]
[Tooltip("Display raycasts in editor (runtime)")]
public bool showDebugRays = true;
private float debugRayLifetime = 0.4f;
private Vector2[] sensors;
private Vector2[] lastPositions;
[HideInInspector] public bool playing = false;
private void Awake()
{
InitializeSensors();
if (playOnStart)
Play();
}
/// <summary>
/// Resets hit position and starts raycasting
/// </summary>
public void Play()
{
//Reset lastPositions
for (int i = 0; i < lastPositions.Length; ++i)
lastPositions[i] = GetTransformPoint(sensors[i]);
//Reset hitObjects
hitObjects.Clear();
playing = true;
}
/// <summary>
/// Stops the raycasting
/// </summary>
public void Stop()
{
playing = false;
}
public int frames = 0;
private void FixedUpdate()
{
if (!playing)
return;
frames++;
if (frames % raycastRate != 0)
return;
frames = 0;
RaycastProcedure();
}
/// <summary>
/// Initializes sensor positions
/// </summary>
public void InitializeSensors()
{
sensors = new Vector2[sensorCount];
lastPositions = new Vector2[sensorCount];
float d = 1f / (sensorCount - 1);
float lerpValue = 0f;
for (int i = 0; i < sensorCount; ++i)
{
sensors[i] = Vector2.Lerp(startPoint.localPosition, endPoint.localPosition, lerpValue); //Set sensors between startPoint and endPoint evenly
lerpValue += d;
}
}
/// <summary>
/// Returns position relative to target transform
/// </summary>
private Vector2 GetTransformPoint(Vector2 v)
{
return target.TransformPoint(v);
}
private void RaycastProcedure()
{
//Raycast order (assuming all are enabled)
//1. Horizontal raycasts
//2. Intersection top raycasts
//3. Intersection bottom raycasts
//4. Vertical raycasts
for (int i = 0; i < sensors.Length; ++i)
{
Vector2 currentPosition = GetTransformPoint(sensors[i]);
//Horizontal
if (horizontalRaycasts)
Raycast(lastPositions[i], currentPosition, RaycastType.Horizontal);
//Raycast in intersection shape ( \ shape ) Top-to-Bottom
if (intersectionRaycastsTop && i > 0)
Raycast(lastPositions[i], GetTransformPoint(sensors[i - 1]), RaycastType.IntersectionTop);
//Raycast in intersection shape ( / shape ) Bottom-to-Top
if (intersectionRaycastsBottom && i < sensorCount - 1)
Raycast(lastPositions[i], GetTransformPoint(sensors[i + 1]), RaycastType.IntersectionBottom);
//Set last position
lastPositions[i] = currentPosition;
}
//Raycast from startPoint to endPoint (Vertical)
if (verticalRaycasts)
Raycast(lastPositions[0], lastPositions[sensorCount - 1], RaycastType.Vertical);
}
private RaycastHit2D[] hits;
private enum RaycastType { Horizontal, Vertical, IntersectionTop, IntersectionBottom };
private void Raycast(Vector2 from, Vector2 to, RaycastType rayType)
{
bool hitDetected = false;
hits = Physics2D.LinecastAll(from, to);
//Iterate results
foreach (RaycastHit2D hit in hits)
{
//Check if collider exists and is not the collider attached to target transform (self)
if (hit.collider != null && hit.collider.transform != target)
{
hitDetected = true;
HandleHit(hit);
}
}
#region Debug rays
if (showDebugRays)
{
Color lineColor = Color.white;
switch (rayType)
{
case RaycastType.Horizontal:
lineColor = Color.white;
break;
case RaycastType.Vertical:
lineColor = Color.cyan;
break;
case RaycastType.IntersectionTop:
lineColor = Color.magenta;
break;
case RaycastType.IntersectionBottom:
lineColor = Color.yellow;
break;
}
//Red whenever it hits something
Debug.DrawLine(from, to, hitDetected ? Color.red : lineColor, debugRayLifetime);
}
#endregion
}
private HashSet<Collider2D> hitObjects = new HashSet<Collider2D>();
private void HandleHit(RaycastHit2D hit)
{
//Ignore objects that have already been hit
if (hitObjects.Contains(hit.collider))
return;
else
hitObjects.Add(hit.collider);
Debug.Log("Hit detected! gameObject's name: " + hit.collider.gameObject.name);
if (stopAfterFirstHit)
Stop();
if (showDebugRays)
{
//Draw a + symbol on hit point
Debug.DrawRay(hit.point + new Vector2(0, 0.2f), Vector2.down * 0.4f, Color.red, debugRayLifetime * 1.5f);
Debug.DrawRay(hit.point + new Vector2(-0.2f, 0), Vector2.right * 0.4f, Color.red, debugRayLifetime * 1.5f);
}
//////////////////////////////////////////////////////////////////
// You probably want to implement a interface or something here //
//////////////////////////////////////////////////////////////////
}
#region Gizmos
private void OnDrawGizmos()
{
if (Application.isPlaying)
{
Gizmos.color = Color.green;
foreach (Vector2 v in sensors)
Gizmos.DrawWireSphere(GetTransformPoint(v), 0.075f);
}
if (startPoint != null && endPoint != null)
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(startPoint.position, 0.1f);
Gizmos.DrawWireSphere(endPoint.position, 0.1f);
}
}
#endregion
}