TLDR: Is there a way to limit number of collisions a rigidbody/collider can enter per fixedUpdate?
I am building a 2D simulator where thousands of rigidbodies continously collide with one another. I do not have to be deterministic but I have to maximize the number of rigidbodies. However FPS drops significantly at about 500 rigidbodies.
two biggest responsible parties are:
Physics2D.CompileContactCallbacks 17%
Physics2D.Step 15%
Each rigidbody has an OnCollisitonStay2D() method. I found I can minimize the impact of the code inside with a counter as below;
int totalCollisionsThisFrame =0;
private void LateUpdate()
{
totalCollisionsThisFrame = 0;
}
private void OnCollisionStay2D(Collision2D collision)
{
if (totalCollisionsThisFrame < 2)
{
animal.Collide(collision.collider);
totalCollisionsThisFrame++;
} else {
//Reserved
}
}
However, since the OnCollisionStay2D is still called, it impacts unncessarily.
So to remove the rigidbody from collisions after the first 2 collision detection, I tried the following;
A). changing the layer once the number of total collisions are above 2 and chaning it back in the LateUpdate() so it wont be part of collision calculations…
This was very inefficient.
B). Putting the rigidbody to sleep using rigidbody2D.Sleep() once the number of total collisions are above 2 and Wake() in LateUpdate()… also very inefficient.
C). IgnoreCollision() doesn’t help either. It is not just in efficient, because I don’t keep the data (for efficiency purposes) there is no way of reverting it back. There is no method to undo all ignoreCollisions with one go.
D) I considered ECS for improving efficiency however I can not find any tutorial that uses both ECS, colliders and joints. If you know any it would be appreciated.
Long story short; my question is;
- Is there a way to limit number of collisions a rigidbody/collider can enter per fixedUpdate?
Thanks in advance