Search Unity

Trying to stop agents fighting over same destination

Discussion in 'Navigation' started by shadow-river, Dec 29, 2014.

  1. shadow-river

    shadow-river

    Joined:
    May 29, 2013
    Posts:
    63
    Hi, I've been working on a rts using unity navigation and I was wondering if there was a way to stop 2 or more nav mesh agents fighting over the same destination.

    for instance im using this click to move script to move 2 or more agents.

    Code (CSharp):
    1. if(Input.GetMouseButtonDown (1) && selected == true)
    2.         {
    3.             Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    4.             RaycastHit hit;
    5.            
    6.             if(Physics.Raycast(ray, out hit, 100))
    7.             {
    8.                 agent.SetDestination (hit.point);
    9.                 anim.SetBool("walk",true);
    10.             }
    11.         }
    and im using this when the agents reach there destination

    Code (CSharp):
    1. if(agent.remainingDistance <= float.Epsilon)
    2.         {
    3.             anim.SetBool("walk",false);
    4.         }
    is there a way to stop the agents from fighting over that one spot and just take the nearest available position.

    If anyone could help it would be greatly appreciated.
     
  2. kenlem

    kenlem

    Joined:
    Oct 16, 2008
    Posts:
    1,630
    As long as you use the same destination for each nav mesh, they are going to try to reach the same point.

    1. You can change the stopping distance so the agent stops when close to the destination point.

    2. You can give each unit its own unique destination point.
     
  3. shadow-river

    shadow-river

    Joined:
    May 29, 2013
    Posts:
    63
    yeah I've messed around with the stopping distance it didn't give the effect I wanted. I was wondering, in order to give each unit its own unique destination point could you use "Random.insideUnitSphere" along with the mouse click.
    something like this....

    Code (CSharp):
    1. Vector3 uniquePoint = Random.insideUnitSphere * mouseHit;
    2.          NavMeshHit hit;
    3.          NavMesh.SamplePosition( uniquePoint, out hit, mouseHit, 1);
    4.          Vector3 finalPosition = hit.position;  
    5.         agent.SetDestination (finalPosition);
    6.  
    not to sure if that would work haven't tested it yet. I'm pretty sure I have got a few things wrong there though.
     
    Last edited: Dec 29, 2014