2D collisions on a Texture2D with transparent areas

I have a 2D texture assigned on a plane with some transparent areas : 1 Black is transparent and white is solid. The texture is procedurally generated.

I need the white areas to have colliders, so that rigidbodies could fall through black areas and land on white ones.

Is there any way to do this?

You’ll have to do collisions manually- there’s no way of tweaking the physics engine to have this kind of functionality. However, if you are happy with having somewhat unrealistic collisions, it is possible to check the UV coordinates of the mesh against the mesh’s texture, to check if it’s black or white- you could use this with manual raycast collisions.

public bool CheckBlackWhite(Ray castThis)
{
    RaycastHit hit;
    if(Physics.Raycast(Ray, out hit))
    {
        // Just in case, also make sure the collider also has a renderer
        // material and texture. Also we should ignore primitive colliders.
        Renderer hitRender = hit.collider.renderer;
        MeshCollider meshCollider = hit.collider as MeshCollider;
        if (hitRender == null || hitRender.sharedMaterial == null ||
        hitRender.sharedMaterial.mainTexture == null || meshCollider == null)
            return false;
        Texture2D hitTex = hitRender.material.mainTexture;
        Vector2 pixelUV = hit.textureCoord;
        pixelUV = new Vector2(pixelUV.x * tex.width, pixelUV.y * tex.height);

        // this is the important bit!
        // Make sure that the texture has 'isReadable' set to true, or this won't work.
        Color pixelValue = hitTex.GetPixel(pixelUV.x, pixelUV.y);

        // returns true if the colour hit is light, false if it's dark
        return (pixelValue.grayscale > 0.5f);
    }
}

Otherwise, you can precache your colliders if it’s procedurally generated by creating a mesh that matches the black and white sections and using a mesh collider, but that’s way more difficult. I hope this is enough for you! I think you might be able to use certain other Physics functions in a similar way to get more accurate results, but of course that would be slower.

Hello,

I am sorry for asking a question on this old topic (and for my English level), but the title of the topic is perfectly adapted to my question.

syclamoth suggests two ways to check the collisions on a texture with transparent areas:

  • check if the pixel is transparent
  • create a mesh adapted to the shape on the texture
    The both works.

My question is : what is the best solution concerning the memory ?

I read that set a texture “readable” doubles the memory needed, because a copy of the data is done. But if I do a mesh corresponding to a complicated 2D shape, I need a lot of polygones in my world.

Considering I have a lot of objects and my game has to work on mobile devices, is someone knows what is the best solution ?

Thank you for your help