Search Unity

2D physics optimization

Discussion in 'Physics' started by IMYT, May 25, 2021.

  1. IMYT

    IMYT

    Joined:
    Mar 4, 2016
    Posts:
    3
    Hi,

    I'm making a procedural 2d terrain system with automatically generated polygon 2d colliders. The terrain shape can be very complex sometimes and as a consequence, the colliders themselves are also very complex too (with a lot of points/path). The physics update becomes the biggest bottleneck very quickly.
    In my experiments, when I split a terrain into multiple GameObjects, it runs significantly faster them put all the terrain collider data into one single GameObject. I guess the physics engine is doing some sort of culling when there are multiple GameObjects. Is there a different way to take advantage of the culling system without splitting the terrain into multiple GameObjects? I heard that GameObjects are very valuable resources and I don't want to waste them too much.

    Thanks.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    The physics engine knows nothing about GameObject or Colliders. Yep, nothing whatsoever. It uses shapes. If you look in the Collider2D "Info" in the inspector, it shows you a count of how many real physics shapes are being used. Cost can be generating them all if there are tens of thousands (etc) but when they're in, cost will be low because they don't do anything. Unless of course you're moving them all.

    Are you really interested in the interior of this "terrain" because you didn't post any images or indicate what you mean by this. Why not use an EdgeCollider2D for the surface of it only? If you need to join multiple ones then you can use the adjacent edge feature to virtual join them etc.
     
    IMYT likes this.
  3. IMYT

    IMYT

    Joined:
    Mar 4, 2016
    Posts:
    3
    Hi MelvMay,

    Thanks very much for your help. We have checked the CPU profiler again and it seems that our main bottleneck was in shape creating code instead of physics update. We have optimized the shape creation code and now it's much faster!

    About what we are trying to do, we are making a destructible 2d terrain system for a top-down shooting game using marching squares. It is very similar to https://imgur.com/gallery/lMrgZ.

    Thanks again.