Home > Enterprise >  How can I detect transparent areas in a sprite in Unity
How can I detect transparent areas in a sprite in Unity

Time:04-28

I have a 1024x1024 pixel sprite with some transparent areas in it. I am rendering it on a game scene using Sprite Renderer. Is there any way check whether the pixel at mouse position is transparent or not when the mouse is hovered over it.

CodePudding user response:

We could cast ray and get the world position of our hit point, Here I am assuming your SpriteRenderer has a collider.

private RaycastHit CastRay()
{
    RaycastHit hit;
    Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
    Physics.Raycast(ray, out hit);
    return hit;
}

Then we need a method to convert that world space into texture coordinates

public Vector2 TextureSpaceCoord(Vector3 worldPos) {
    float ppu = _sprite.pixelsPerUnit;

    Vector2 localPos = transform.InverseTransformPoint(worldPos) * ppu;

    var texSpacePivot = new Vector2(_sprite.rect.x, _sprite.rect.y)   _sprite.pivot;
    Vector2 texSpaceCoord = texSpacePivot   localPos;

    return texSpaceCoord;
}

Once we get the texture coordinates we could just use GetPixel() of Texture2D to get the color

private void PickColor()
{
    RaycastHit hit = CastRay();
    if (hit.collider != null)
    {
        Vector2 coord = TextureSpaceCoord(hit.point);
        Color selectedColor = _sprite.texture.GetPixel((int) coord.x, (int) coord.y);

        // Here you can check if color is transparent
        if(selectedColor == Color.clear){
            // do stuff
        }
    }
}

You could call the PickColor() in Update(), _camera would be Camera.main and _sprite would be the Sprite of your SpriteRenderer

  • Related