Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Question Generate Physics Shape from Sprite?

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

  1. CaseyHofland

    CaseyHofland

    Joined:
    Mar 18, 2016
    Posts:
    629
    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.