Search code examples
unity-game-enginespritemeshtransparentmesh-collider

Different ways to detect size of image on mesh versus size of mesh


I'm creating a puzzle game that generates random sized pieces with 2D meshes. The images contain transparent portions and sometimes a piece is completely transparent. I need to detect what percentage of a piece is transparent. One way I found to do this is to go pixel by pixel. I posted my solution to this HERE. However, this process adds a few seconds during loading which I'd like to avoid and I'm looking for other ideas

I've considered using the selection outline of a MeshCollider to somehow to get a surface area I can compare to the surface area of the mesh but everything I find is on the rendering of outline with specialized shaders. Does anyone have any ideas on to solve this?

Example puzzle piece with transparent pixels around top of head..

enter image description here


Solution

  • 1) I guess you could add a PolygonCollider2D to your sprite and use its Path for the outline and calculation of the surface area. Not sure however if this will be faster.

    PolygonCollider2D.GetPath:

    A path is a cyclic sequence of line segments between points that define the outline of the Collider

    Checking PolygonCollider2D.GetTotalPointCount or path length may be good enough to determine if the sprite is 'empty'.

    Sprite.vertices, Sprite.triangles may also be helpful.

    2) You could also improve performance of your first approach:

    • instead of calling GetPixel as you do now use GetPixels or GetPixels32 and loop through the array in one for loop.

    Using GetPixels can be faster than calling GetPixel repeatedly, especially for large textures. In addition, GetPixels can access individual mipmap levels. For most textures, even faster is to use GetPixels32 which returns low precision color data without costly integer-to-float conversions.

    • check only every 2nd or nth pixel as it should be good enough for approximation
    • limit number of type casts