Search Unity

Question Generate Physics Shape from Sprite?

Discussion in 'Scripting' started by CaseyHofland, Sep 17, 2020.

  1. CaseyHofland

    CaseyHofland

    Joined:
    Mar 18, 2016
    Posts:
    615
    Hi there, I'm looking for an algorithm that can generate a physics shape / an outline of points from a png. Bonus points if the algorithm can handle holes. Doesn't matter how unperformant it is btw, I have asynchronous wiggle room on this one.



    If you are interested, here's my issue:
    I have something that creates shapes at runtime, and many of them. Currently I'm using Sprite.Create for this, which has an option generateFallbackPhysicsShape which generates an outline of points from a png. But... it's inaccurate.

    WhatsApp Image 2020-09-12 at 11.26.59.jpeg
    (Sucks butt, especially annoying for stairs :mad:)

    Now, all I would need is a tolerance value like so:
    2D_CustomPS_image_3.png

    And if I set it to 1 I get this:
    27f042a7-6f98-4de2-ac3b-3fd25177dea5.jpg
    (Beauty and perfection :rolleyes:)

    However... this tolerance value is not available at runtime. So I need my own algorithm to do it. Sadly googling "generate png outline" only gives you photoshop tutorials or bitmap stuff, I'm really looking for a raw, shape-searching algorithm for pngs.

    I'm not afraid for something unperformant either, I have the wiggle room to split the function across frames or run it asynchronously. Getting thousands of points isn't a problem as I already use an algorithm to reduce those as well.

    I've already tried looking in Unity's source code, but even if I dig deep, the GenerateOutline function is hidden in a blackbox. If someone at Unity reads this, I would love if you could sneak a peek for me at your algorithm.
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    If you dont care about performance, just GetPixels, compare alpha < threshold to get a point cloud, then calculate a concave hull.
    It's 'Simple' kek
     
    PraetorBlue likes this.