Simple AI Behaviors: Fleeing
Like us, sometimes game objects just need to get away, whether it be from each other, our player, or our player’s missiles, sticky grenades, and vehicle roadkills. Similarly to the seek steering behavior discussed previously, flee provides those game objects with the means to steer towards a specified location. However, instead of the location being aligned with a target, it’s positioned away from the threat, simulating an escape.
The same velocities and forces (current, desired, and steering) are shared between seek and flee, and each velocity/force still functions the same except for the desired velocity as shown below:
Current velocity is the current force driving an object in a direction.
Desired velocity is now the vector pointing from the target towards the character, or in the opposite direction of the target.
Steering velocity represents the difference between the desired and current velocities.
In order to get the desired velocity for fleeing, the target’s position must be subtracted from the character’s, whereas with seeking, the character’s position is subtracted. That difference between positions represents the easiest possible escape route for the character so if it’s going to survive, it should now steer in that direction.
Just like with the seek path, the steering velocity is added back to the character’s current velocity which results in a flee path that pushes the character away from the target and towards the desired escape route each frame.
To visualize this in Unity, I’ve added a red capsule game object to the seeking scene shown previously and given it it’s own Fleeing.cs script. Again, the fleeing behavior and method uses nearly the same setup, velocities, and forces as the one for seeking except for desired velocity. However, the fleeing object now also needs to reference the distance between itself and the target before attempting an escape.
A simple if() statement can be used to check the Vector3.Distance() between each object against a max distance variable, but If not, the fleeing object will continuously move away from the target regardless of it’s proximity (maybe a good thing depending on the target).
The fleeing method broken into five sections with descriptions:
Once the method is combined, and with an object assigned to seek it out, the fleeing object will only act if that seeker comes within the specified range, allowing it to live to flee another frame.