Search Unity

Question How to stop enemies from huddling and surrounding the player (2D)

Discussion in 'Navigation' started by la3eb, Nov 20, 2021.

  1. la3eb

    la3eb

    Joined:
    Feb 11, 2017
    Posts:
    12
    Hello everyone,

    I am trying to make a 2D game where enemies move and surrond the player here is the code for following the player

    Code (CSharp):
    1.  if (Vector3.Distance(transform.position, tower.position) > minDistance)
    2.         {
    3.            
    4.             //transform.position = Vector2.MoveTowards(transform.position, tower.position, speed * Time.deltaTime);
    5.  
    6.  
    7.             Vector3 movePosition = transform.position;
    8.  
    9.             movePosition.x = Mathf.MoveTowards(transform.position.x, tower.transform.position.x, speed * Time.deltaTime);
    10.             movePosition.y = Mathf.MoveTowards(transform.position.y, tower.transform.position.y, speed * Time.deltaTime);
    11.  
    12.             GetComponent<Rigidbody2D>().MovePosition(movePosition);
    13.  
    14.  
    15.         }
    It works perfectly when there is one enemy (Enemies are in red) (Player is in blue)

    upload_2021-11-20_22-26-37.png
    But when I have a lot of enemies they just freeze as so but I want them to surround the player without colliding with each other like so

    upload_2021-11-20_22-28-49.png

    Thanks in advance
     

    Attached Files:

  2. Pencode

    Pencode

    Joined:
    Jul 9, 2021
    Posts:
    1
    Hello there, Ia3eb!
    Now, I'm no expert myself, but perhaps adding a collider2D component to your enemies might solve your problem. Your enemies would collide into each other, but I think they may surround the player.
    I'm sorry if this doesn't provide too much assistance. I am a beginner myself.
    Good luck, Ia3eb!
     
  3. la3eb

    la3eb

    Joined:
    Feb 11, 2017
    Posts:
    12
    Thank you for your response the enemies already have the collider that's why they aren't colliding in the photo above I just don't want them to go in a line like photo one