I want my enemies to follow the player, stop at a certain distance and when enemy is within that distance he will walk away.
[SerializeField] Transform target;
[SerializeField] float followRange = 5f;
[SerializeField] float fleeRange = 2f;
NavMeshAgent navMeshAgent;
float distToTarget = Mathf.Infinity;
public Animator anim;
[SerializeField] bool hasTarget = false;
[SerializeField] bool hasDanger = false;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
}
void Update()
{
distToTarget = Vector3.Distance(target.position, transform.position);
if(distToTarget <= followRange && distToTarget >= (fleeRange - 1f))
{
hasTarget = true;
}
else
{
hasTarget = false;
}
if(distToTarget <= fleeRange)
{
hasDanger = true;
}
else
{
hasDanger = false;
}
if(hasTarget && hasDanger)
{
navMeshAgent.SetDestination(transform.position);
}
HasTarget();
HasDanger();
}
void HasTarget()
{
if(hasTarget)
{
navMeshAgent.SetDestination(new Vector3 (target.position.x, transform.position.y, target.position.z));
anim.SetInteger("Status_walk", 1);
}
else
{
navMeshAgent.SetDestination(transform.position);
anim.SetInteger("Status_walk", 0);
}
if(hasDanger){return;}
}
void HasDanger()
{
if(hasDanger)
{
Vector3 toTarget = target.position - transform.position;
if(Vector3.Distance(target.position, transform.position) < fleeRange)
{
Vector3 targetPosition = toTarget.normalized * -fleeRange;
navMeshAgent.SetDestination(targetPosition);
}
}
if(hasTarget){return;}
}
This code kinda works, but they just walk up to the target, walk away, walk back and so on.