Hello!
I’m currently needing to do a lot of intense manual checks at very specific times such as Unity - Scripting API: Rigidbody2D.OverlapCollider and wondered if there are any further optimisations I should be worried about, or if this function already does a lot of rejecting colliders it can’t touch?
My suspicion is that the function would call functions that are already optimised to reject any collision geometry that would potentially not touch so further optimisations on my part are needless (I have a LOT of colliders in the level)…
Thanks!
Isn’t there a broad-sweep system or some kind of grid acceleration structure built-in that automatically figures this stuff out? Like if it seems even remotely likely that objects are close enough to warrant doing a more in-depth collision test?
The main thing I do is making sure the combinations of what can collide with what, in the physics settings, is minimized as much as possible so that it’s not trying to check things unnecessary. If you can isolate the objects to like specific layers or whatever.
That said, its a general system and it doesn’t have knowledge of your intentions, so if you have insider knowledge that maybe you can disable the physics colliders temporarily or something, until you know that it’s likely a good time to start doing physics tests, then possibly that might help performance?
1 Like
When you perform any spatial physics query in 2D, it uses the same broadphase tree that standard collision detection uses. That is based upon overlapping AABB.
As an example, if you perform a OverlapCircle, we first calculate its AABB. We then query the world with that AABB and it returns us potentials. This part is super fast. We can then perform narrow-phase (accurate) testing for the specific shapes. This part is much slower.
The same goes for casts but in that case, the AABB is the union of the shape at the start point and the end point. The rest is the same. The only difference here is that a very large cast can potentially create a large AABB to find shapes in, especially if on angles.
This is why performing a cast over small distances is better. Performing sweeps to “infinity” can take longer so always specify reasonable distances if you can.
You should be able to see this by adding hundreds of colliders into the world then perform a check way outside of those colliders. You should find that it is fast and does not related to how many items there are in the world.
We would not leave you with slow queries, honest!
4 Likes
Wow nice tips, thanks!
I can rest easy knowing it’s going to be my own foolishness if it’s slow 
1 Like