-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathEnvironmentQueryRunner.cs
More file actions
83 lines (65 loc) · 3.02 KB
/
EnvironmentQueryRunner.cs
File metadata and controls
83 lines (65 loc) · 3.02 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
using UnityEngine;
namespace EQS {
/// <summary>
/// MonoBehaviour that runs an EnvironmentQueryAsset each frame or on demand and exposes the best result.
/// Assign a query asset, set querier (this transform) and optional target; read BestPosition / LastResult.
/// </summary>
public class EnvironmentQueryRunner : MonoBehaviour {
#region Fields
[SerializeField] EnvironmentQueryAsset query;
[SerializeField] [Tooltip("Optional. If set, context target is updated from this.")]
Transform target;
public bool RunEveryFrame { get; set; } = true;
[SerializeField] [Tooltip("Draw best (green) and candidates (blue/red) when selected and playing.")]
bool drawGizmos = true;
EQSContext context;
EQSRunResult lastResult;
#endregion
public EnvironmentQueryAsset Query => query;
public EQSRunResult LastResult => lastResult;
public bool HasValidResult => lastResult.Success;
public Vector3 BestPosition => lastResult.Success ? lastResult.BestPosition : transform.position;
protected void Start() {
if (query != null) {
RunEveryFrame = query.Strategy == AgentStrategy.Continuous && !query.RunOnce;
if (!RunEveryFrame) RunQuery();
}
}
protected void Update() {
if (RunEveryFrame && query != null) RunQuery();
}
/// <summary>
/// Run the assigned query once and store the result in LastResult.
/// </summary>
public void RunQuery() {
if (query == null) return;
context = EQSContext.From(transform, target);
lastResult = query.Run(context);
}
/// <summary>
/// Run a specific query with optional target override.
/// </summary>
public EQSRunResult RunQuery(EnvironmentQueryAsset asset, Transform targetOverride = null) {
EQSContext ctx = EQSContext.From(transform, targetOverride != null ? targetOverride : target);
return asset != null ? asset.Run(ctx) : EQSRunResult.Failure();
}
#if UNITY_EDITOR
const float NormalGizmoLength = 3f;
void OnDrawGizmosSelected() {
if (!drawGizmos || !Application.isPlaying || query == null) return;
if (lastResult.AllCandidates == null) return;
for (int i = 0; i < lastResult.AllCandidates.Count; i++) {
QueryPoint p = lastResult.AllCandidates[i];
if (lastResult.Success && i == lastResult.BestIndex) {
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(p.Position, 0.5f);
} else {
Gizmos.color = p.Score < 0.05f ? Color.red : Color.blue;
Gizmos.DrawWireSphere(p.Position, 0.2f);
}
Gizmos.DrawLine(p.Position, p.Position + p.Normal * NormalGizmoLength);
}
}
#endif
}
}