Home > front end >  Enemy chase limit C# Unity
Enemy chase limit C# Unity

Time:08-03

I have been struggling with something for some time now, I was wondering how do I limit how many enemies can chase the player at once? I want to limit it to 3 enemies. I would really appreciate if anyone can figure this out for me.

Here is my code:

 private void ChasePlayer()
 {
    enemyAmount  ;
    enemyChasing = true;
    if (enemyAmount <= 3 && enemyChasing == true) { return; }
    {
        if (Vector2.Distance(target.position, transform.position)
        <= followRadius && Vector2.Distance
        (target.position, transform.position) > attackRadius
        && CurrentState != EnemyState.stagger)
        {
            Vector3 temp = Vector2.MoveTowards(transform.position,
            target.position, speed * Time.deltaTime);
            Animator(temp - transform.position);
            myRigidbody.MovePosition(temp);
            animator.SetBool("Moving", true);
        }
        else if (enemyAmount > 3)
        {
            enemyChasing = false;
            animator.SetBool("Moving", false);
        }
        else if (Vector2.Distance(target.position,
        transform.position) > followRadius)
        {
            animator.SetBool("Moving", false);
        }
    }
}

CodePudding user response:

You could track the number of enemies currently chasing the player. Maybe using a static integer. And if the number exceeds your required limit, return at the beginning of the function which makes the enemies chase the player.

CodePudding user response:

Got it! You need to have a separate if for the return statement. Currently, your lower block is running in all cases.

Try this. 
 private void ChasePlayer()
{
    enemyAmount  ;
    enemyChasing = true;
    if (enemyAmount > 3 && enemyChasing == true) {return;}
else
    {
        if (Vector2.Distance(target.position, transform.position) <= followRadius && Vector2.Distance
        (target.position, transform.position) > attackRadius
        && CurrentState != EnemyState.stagger)
        {
            Vector3 temp = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
            Animator(temp - transform.position);
            myRigidbody.MovePosition(temp);
            animator.SetBool("Moving", true);
        }
        else if (enemyAmount > 3)
        {
            enemyChasing = false;
            animator.SetBool("Moving", false);
        }          
        else if (Vector2.Distance(target.position, transform.position) > followRadius && enemyAmount >= 4)
        {
            animator.SetBool("Moving", false);
        }
    }
}
  • Related