- Home /
How to add avoidance and chase behavior
I would like to implement the type of behavior where a group of prey is evading from a predator like this Game
I tried to write the script this way but I don't get the desired motion the prey just moves forward.
public Transform target;
public float damping;
public float drivespeed;
void Update () {
transform.Translate(Vector3.forward * Time.deltaTime * -drivespeed);
Quaternion rotation = Quaternion
.LookRotation(target.position - transform.position);
transform.rotation = Quaternion
.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
Answer by Double-V · Aug 01, 2018 at 01:12 PM
What you can do is put a sphere collider with trigger enabled on the attacker, or even better, make it a child object with that sphere trigger (becuase maybe you already have some triggers on the attacker).
Then make a script that every time a pray enters this trigger, gets the prey's AI and notifies it that an attacker is nearby, something like this:
void OnTriggerEnter(Collider other)
{
if(other.gameobject.layer == LayerMask.NameToLayer("Prey"))
{
other.gameobject.GetComponent<YourPreyScript>().NotifyOfAttacker();
}
}
And this script also notifies the prey when the attacker is no longer in range, but it's a good idea too do that with a delay, because without a delay the prey would just instantly stop after exiting the attacker's sphere.
void OnTriggerExit(Collider other)
{
if(other.gameobject.layer == LayerMask.NameToLayer("Prey"))
{
other.gameobject.GetComponent<YourPreyScript>().Invoke("AttackerFarAway", 5f);
}
}
Now inside the prey's script you could have something like this:
private bool attacker_close = false;
private GameObject attacker;
void Start()
{
attacker = Gameobject.Find("Attacker");
}
void Update()
{
if(attacker_close)
{
RunAway();
}
}
public void NotifyOfAttacker()
{
attacker_close = true;
}
public void AttackerFarAway()
{
attacker_close = false;
}
void RunAway()
{
Vector3 attacker_position = attacker.transform.position;
Vector3 dir = transform.position - attacker_position;
//do the moving and rotating in direction of dir, I don't know what kind of movement setup you have
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612172001im_/https://answers.unity.com/themes/thub/images/avi.jpg)