Hello everyone!
I’m making a 2D game with a terrain made using marching squares. I’m using the Custom Collider 2D component with edges to “draw” the marching square collider. Here is what a chunk of 25x25 looks like:
The thing is that I want the terrain to be diggable. This means I have to regenerate the collider each time a tile has been dug. The problem is that it’s not performant on the physic side. Calling CustomCollider2D.SetCustomShapes takes 0.2ms and then Physics2D.FindNewContacts takes around 0.5ms. So if I dig between 4 chunks we have a total of 2.8ms which is too much for me.
I tried to reduce the number of shapes in the custom collider but it didn’t change anything. One thing that reduced those spikes is to reduce the chunk’s size. So for example, using 5x5 chunks of 5x5 nodes instead of using 1x1 chunk of 25x25 nodes. But if I want to pool chunks, I’ll want to activate multiple chunks which will also call Physics2D.FindNewContacts when enabled. So the result is the same. Here is me enabling/desactivating a chunk:
I wanted your opinion on my issue:
- Do you think using the custom collider 2d is the way to go? If yes, do you have any idea how to reduce those physic spikes?
- If the colliders in Unity are not made to be edited at runtime, do you think making a custom physic engine for the terrain is worth it?
Thank you for reading 
The CustomCollider2D gives you direct access so is very fast but it’s practically impossible to remotely debug this for you TBH.
When you set shapes, if you’re setting all of them then maybe that’s the issue. That call allows you to change a subset of only the shapes that change if you wish.
FindNewContacts are the physics engine finding new contacts for new shapes. If you’re replacing everything then maybe it’s that but it’s all a guess.
Really though, I can only answer specific questions about this and not really tell you how you could improve what you’re doing as it’s not really clear.
I am more than happy to provide any information you need though on how it works; I wrote it.
1 Like
Whilst it doesn’t directly help with your case, here are some of the original dev videos where lots of shapes are being changed in realtime at high framerates so it shows it’s more than possible. 
1 Like
Thanks for the answer! It has given me new ideas on how to potentialy improve the performance
. As you guessed I’m replacing all shapes inside the CustomCollider2D each time I’m regenerating the chunk. I’ll try to separate the collider into smaller shapes and update only the relevant one.
I have one small question for you if you don’t mind: Is having a lot of shapes inside the CustomCollider2D a problem? Should I tried to reduce the number as much as possible?
Edit: (Is the code you used in your 3 videos in the PhysicsExample2D demo on Github? I can’t find it :() Nevermind I found it!
1 Like
Please feel free to ask away about this either here or DM me.
1 Like