Search Unity

Lots of rigidbodies

Discussion in 'Physics' started by Neriad, Sep 11, 2019.

  1. Neriad

    Neriad

    Joined:
    Feb 12, 2016
    Posts:
    68
    Hey everyone !

    I'm making a game for quite some time now, and I need to have hundreds of units following a leader (like an army). I have tried many things, but for now I'm trying to make it as optimal as possible as it needs to run on mobile devices.

    I'm having issues with the movement of all those units, and it starts to slow down at 250 rigidbodies moving on screen. Here is the code I have :
    Code (CSharp):
    1.     Vector3 Seek (Vector3 _target)
    2.     {
    3.         return _target - transform.position;
    4.     }
    5.  
    6.     void ApplyForce (Vector3 _force)
    7.     {
    8.         if (this is Basic && distanceFromLeader < 3)
    9.         {
    10.             rb.velocity = Vector3.zero;
    11.             return;
    12.         }
    13.  
    14.         Vector3 force = new Vector3(_force.x, 0, _force.z);
    15.  
    16.         if (force.sqrMagnitude > team.Mover.SqrMaxForce)
    17.         {
    18.             force = force.normalized;
    19.             force *= team.Mover.MaxForce;
    20.         }
    21.         rb.AddForce(force);
    22.  
    23.         if (rb.velocity.sqrMagnitude > team.Mover.SqrMaxVelocity)
    24.         {
    25.             rb.velocity = rb.velocity.normalized;
    26.             rb.velocity *= team.Mover.MaxVelocity;
    27.         }
    28.  
    29.         //transform.forward = Vector3.Lerp(transform.forward, _force.normalized, 5 * Time.deltaTime);
    30.         transform.forward = Vector3.Lerp(transform.forward, team.Mover.Leader.transform.forward, 5 * Time.deltaTime);
    31.  
    32.         if (transform.position.y > 0 || transform.position.y < 0)
    33.             transform.position = new Vector3(transform.position.x, 0, transform.position.z);
    34.         //Debug.DrawRay(transform.position, force, Color.white);
    35.     }
    36.  
    37.     public void Flock (Vector3 _goalPos)
    38.     {
    39.         currentForce = Seek(_goalPos).normalized;
    40.         ApplyForce(currentForce * 50);
    41.     }
    Flock is called foreach units inside the FixedUpdate of the leader (moving 250 untis in the same FixedUpdate). How can I optimize this so I get better performance with the same crowd movement feeling ?
     
    Last edited: Sep 11, 2019