Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Marching squares colliders

Discussion in '2D' started by madks13, Mar 19, 2018.

  1. madks13

    madks13

    Joined:
    May 8, 2016
    Posts:
    173
    Hello,

    i'm having a problem with the collider of a mesh generated at runtime.
    As mentionned in the title, i'm using Marching Squares to generate 2D tiled terrain. This is working well. But when i try to add a collider it doesn't seem to work. I'm trying to add a MeshCollider :
    Code (CSharp):
    1. collider = GetComponent<MeshCollider>();
    2.  
    3. ...(triangulation)
    4.  
    5. collider.sharedMesh = null;
    6. collider.sharedMesh = filter.sharedMesh;
    The setting of the mesh in the collider is done each time i finish triangulating vertices.
    I'm only creating a flat mesh, meaning there is no depth to it, only the visible front side of it is created to reduce the number of vertices used.

    While i experimented with colliders, i saw that 3D collider with depth of 0 don't collide (obviously). However, when i added depth to the terrain, it still didn't collide. Seems like the collider wasn't even there.

    As i said, this is a 2D terrain, the only reason i'm using Marching Squares is for performance. I have a few questions in relation to all this :
    - Is there a 2D mesh collider?
    - If not, WHY?
    - Am i doing this wrong somehow?
    - If yes, how?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Mesh colliders have lots of limitations, such as not colliding with other mesh colliders (possibly depending on whether or not they're convex, but it sounds like yours is not, so that makes things worse).

    Have you tried raycasting into your mesh? I believe that will work for any type of mesh. (Don't test on the same frame where you create the mesh — you need to give the physics engine time to notice and process the new collider.)

    Of course raycasting may or may not be good enough for your intended use.

    To be honest, in a couple of cases I've given up on wrestling with the physics system and just implemented my own ray-cast code for arbitrary meshes. If you reach that point, let me know and I'll dig up some code to get you started.