Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

MeshCollider.ClosestPoint doesn't work on non-convex meshes

Discussion in 'Scripting' started by EnriqueGato, Aug 9, 2017.

  1. EnriqueGato

    EnriqueGato

    Joined:
    Sep 3, 2016
    Posts:
    81
    I'm not sure if this is a bug, but this has driven me crazy until I realized that I had to enable the "Convex" check on the Mesh Collider in order to make this function work.

    I really need to make ClosestPoint function work without enabling that option. Any idea or workaround?

    Thanks

    meshcollider.png
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    Hm, it does appear to be either a bug or an oversight in the documentation page, as the doc does not mention that the method only works on convex MeshColliders. My guess would be that it's more of a documentation issue, because there are a LOT of things that only work for convex MeshColliders.

    The common workaround for these sorts of things is to split a concave MeshCollider into multiple convex ones. It's not great solution but it works, and IIRC there are some packages available (maybe on the asset store?) that can automatically break apart concave meshes into convex ones.
     
    Wattosan and idbrii like this.
  3. Wattosan

    Wattosan

    Joined:
    Mar 22, 2013
    Posts:
    450
    You are right that it is not mentioned in the documentation of the Collider class. However, it is mentioned in the Physics.ClosestPoint() documentation:
    Unity - Scripting API: Physics.ClosestPoint (unity3d.com)

    "The collider can only be BoxCollider, SphereCollider, CapsuleCollider or a convex MeshCollider."

    I wonder why doesn't it work with a non-convex collider. We really need this to work that way as well.
     
  4. bleater

    bleater

    Joined:
    Apr 19, 2012
    Posts:
    24
    For anyone stumbling across this, you can turn a non-closed mesh collider into a convex mesh collider programmatically thus:
    Code (CSharp):
    1. MeshCollider m = GetComponent<MeshCollider>();
    2. m.convex = true;
    Note from https://docs.unity3d.com/ScriptReference/MeshCollider-convex.html:
    A convex mesh is required by the physics engine to have a non-zero volume. Flat meshes such as quads or planes that are marked as convex will be modified by the physics engine to have a thickness (and therefore a volume) to satisfy this requirement. The thickness of the resulting mesh is proportional to its size and can be up to 0.05 of its longest dimension in the plane of the mesh.​