Search Unity

Dynamic alpha channel on texture to create dynamic transparancy

Discussion in 'Shaders' started by scratchyback, Mar 16, 2015.

  1. scratchyback

    scratchyback

    Joined:
    Mar 16, 2015
    Posts:
    2
    Hello,
    I am quite new to Unity so please forgive my ignorance. In the project I am working on (a 2D project) I need a mechanism to be able to 'poke' a hole through the background image of the game to see another behind it. This poking can be done by the player. It is merely a visual thing.
    To not have to slice up the background into a grid of all the places a player could possibly poke a hole (and then set the transparency of the 'tile' the player clicks...which probably could work...but there will be multiple backgrounds in multiple levels and it is gonna be a pain to slice them all up in grids or replace them if we change the artwork), I was thinking of using a transparency shader. However from what I understand, this shader works with a fixed alpha channel on a texture (material).
    Is there any way to set the alpha channel dynamically in game so the transparent part can be wherever the player clicks on the background? Is a shader even the right direction I need to think of or can this be done any (hopefully simpler) other way.

    I am hoping someone can point me in the right direction.

    Thanks!
     
  2. smd863

    smd863

    Joined:
    Jan 26, 2014
    Posts:
    292
    Should be pretty straight-forward actually. Create a Texture2D using the Alpha8 texture format, and initialize it to white. Whenever the use clicks, use SetPixels() to update the affected pixels and Apply() to load the data into the texture. Create a basic surface shader, add a texture sampler for your Alpha8 texture, and use it for the alpha value. Sample your regular texture for RGB as usual.

    Performance could be an issue if you're updating lots of pixels evey frame, but I doubt you'd have any issues on any PC or laptop. I've even done a coloring book prototype using a similar technique that ran well enough on a first-gen iPad mini.

    You could speed it up by updating the texture with a custom shader and a render target. It would be a bit more setup, but good if you want some more practice working with shaders.
     
  3. scratchyback

    scratchyback

    Joined:
    Mar 16, 2015
    Posts:
    2
    Thanks! It is probably gonna be a challenge for me to get this all to work but I know now I wont run into a dead end.
     
  4. heixenburger

    heixenburger

    Joined:
    May 11, 2017
    Posts:
    2
    Hey, I am trying to achieve same thing. Can you tell me how you did it?