Search Unity

Scrolling Texture2D in Fragment Shader doesn't work with transparent texture

Discussion in 'Shaders' started by PizzaPie, Aug 17, 2019.

  1. PizzaPie

    PizzaPie

    Joined:
    Oct 11, 2015
    Posts:
    107
    The title sums it up pretty much the important part of the shader are this:


    Code (CSharp):
    1. //...
    2. ZWrite Off
    3. Blend SrcAlpha OneMinusSrcAlpha
    4. Cull Off
    5. Lighting OFF
    6.  
    7. //...
    8.  
    9. float _X_Offset;
    10.  
    11. fixed4 frag (v2f i) : SV_Target
    12.             {    
    13.                 float2 offsetUV = i.uv;
    14.  
    15.                 offsetUV.x = offsetUV.x + _X_Offset;
    16.              
    17.                 if (offsetUV.x < 0) {
    18.                     offsetUV.x = 1 + fmod(offsetUV.x, 1);
    19.                 }else if (offsetUV.x > 0)
    20.                 {
    21.                     offsetUV.x = fmod(offsetUV.x, 1);
    22.                 }
    23.  
    24.                 return tex2D(_MainTex, offsetUV);
    25. }
    Nothing special happens in the rest of the shader, same as the one generated by Unity on create.
    So this works, well if the texture has no transparent area, otherwise it fails.
    Did try to use the offset value from _MainTex_ST.
    Tried to change the UVs in the vertex directly and with TRANSFORM_TEX, blind tries though.
    All work as long the texture has no transparent pixels.

    Using Texture2D with SpriteRenderer.

    Any insight on what I am doing wrong or what I am missing will be greatly appreciated.
     
  2. darreney

    darreney

    Joined:
    Oct 9, 2018
    Posts:
    34
    PizzaPie likes this.
  3. PizzaPie

    PizzaPie

    Joined:
    Oct 11, 2015
    Posts:
    107
    Thank you, that fixed it.
    Weird behaviour given that the texture is passed as a 2d array, I did expect the fragment shader to go over the "empty" positions too, guess it is some kind of performance optimization.

    Incase someone else stumbles on this, the solution is to set the Texture's Mesh Type to Full Rect.