| | | 1 | | using UnityEngine; |
| | | 2 | | |
| | | 3 | | // Time escape detector. |
| | | 4 | | // |
| | | 5 | | // The time escape detector checks whether the agent reaches the target before the target reaches |
| | | 6 | | // its target based on the current respective speeds. |
| | | 7 | | public class TimeEscapeDetector : EscapeDetectorBase { |
| | | 8 | | // Minimum speed to prevent division by zero. |
| | | 9 | | private const float _minimumSpeed = 1e-6f; |
| | | 10 | | |
| | 36 | 11 | | public TimeEscapeDetector(IAgent agent) : base(agent) {} |
| | | 12 | | |
| | 12 | 13 | | public override bool IsEscaping(IHierarchical target) { |
| | 13 | 14 | | if (target == null) { |
| | 1 | 15 | | return false; |
| | | 16 | | } |
| | | 17 | | |
| | 11 | 18 | | Transformation agentToTargetTransformation = Agent.GetRelativeTransformation(target); |
| | | 19 | | |
| | | 20 | | // Check if the target has a target of its own. |
| | 19 | 21 | | if (target.Target != null && !target.Target.IsTerminated) { |
| | 8 | 22 | | Vector3 targetRelativePositionToTarget = target.Target.Position - target.Position; |
| | | 23 | | // Check whether the agent is moving head-on towards the target. |
| | 8 | 24 | | if (Vector3.Dot(-agentToTargetTransformation.Position.Cartesian, |
| | 5 | 25 | | targetRelativePositionToTarget) > 0) { |
| | | 26 | | // Check the time-to-hit for the agent and the target. |
| | 5 | 27 | | if (target.Speed < _minimumSpeed) { |
| | 0 | 28 | | return false; |
| | | 29 | | } |
| | 5 | 30 | | float targetTimeToHit = targetRelativePositionToTarget.magnitude / target.Speed; |
| | 5 | 31 | | float agentTimeToHit = agentToTargetTransformation.Position.Range / Agent.Speed; |
| | 5 | 32 | | return targetTimeToHit < agentTimeToHit; |
| | | 33 | | } |
| | | 34 | | // If the agent is chasing the tail of the target, check whether its speed is greater than the |
| | | 35 | | // target's speed. |
| | 3 | 36 | | return target.Speed > Agent.Speed; |
| | | 37 | | } |
| | | 38 | | |
| | | 39 | | // Fall back to checking the relative velocity. |
| | 3 | 40 | | return agentToTargetTransformation.Velocity.Range < 0; |
| | 12 | 41 | | } |
| | | 42 | | } |