Pursue / Evade behavior is different than a simple Seek / Flee behavior. Seek / Flee usually has a still target, or it doesn’t take target movement into consideration, whereas Pursure / Evade anticipates where the target is going to be in the future, and use that as the actual target.
For pursue, this is the list of things needed to calculate the correct steer.
- Calculate the distance between the pursuer and the target, call it DisToTarget.
- Calculate the time it would take flr the pursuer to reach such distance, call it T.
- Find the position of the target in time of T, call it TarPredPos.
- Calculate the direction of desired velocity, which is (TarPredPos – Position of Pursuer).
- Calculate the steering amount, which is (desired velocity – current velocity).
My code looks like this:
Vector2 purPos = GetComponent().position ; Vector2 tarPos = target.transform.position; float disToTarget = (tarPos - purPos).magnitude; float T = disToTarget / MAX_SPEED; Vector2 tarPredPos = tarPos + Target.GetComponent ().GetVelocity () * T; direction = (tarPredPos - purPos).normalized; steer = direction * MAX_SPEED - _actor.GetVelocity(); _actor.SetInput (steer.x, steer.y);
For evade, the logic is completely the same, other than the direction of desired velocity is facing the opposite direction.
After adding some lines to visualize the velocities and accelerations, this is what it actually looks like: