Search code examples
unity-game-engine2dshadersprite

Sprite disappear shader


i am working on Unity 2D platform game. i am using a shader i found here, but when i flip my sprite (scale -1), the sprite disappeared, i have little understand in shader coding, And i didn't found any help on Google, can any one help fixing the shader?. here is the shader:

Properties {
    [PerRendererData] _MainTex ("Main texture", 2D) = "white" {}
    _DissolveTex ("Dissolution texture", 2D) = "gray" {}
    _Threshold ("Threshold", Range(0., 1.01)) = 0.
}

SubShader {

    Tags { "Queue"="Transparent" }
    Blend SrcAlpha OneMinusSrcAlpha

    Pass {

        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct v2f {
            float4 pos : SV_POSITION;
            float2 uv : TEXCOORD0;
        };

        sampler2D _MainTex;

        v2f vert(appdata_base v) {
            v2f o;
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
            o.uv = v.texcoord;
            return o;
        }

        sampler2D _DissolveTex;
        float _Threshold;

        fixed4 frag(v2f i) : SV_Target {
            float4 c = tex2D(_MainTex, i.uv);
            float val = tex2D(_DissolveTex, i.uv).r;

            c.a *= step(_Threshold, val);
            return c;
        }
        ENDCG
    }
}

Solution

  • The sprite is rendered as a rectangle with two triangle of positive index order: clockwise.

    You can change the Shading Mode to Shaded Wireframe to inspect that.wireframe

    And if you flip the sprite (scale -1), the two triangles of the sprite will become counterclockwise. And, counterclockwise triangles will not be rendered by GPU. That's why your sprite disappeared. See also what is a clockwise face in openGL.

    If you want to see your sprite even when it is flipped, you can

    1. create two sprites with the same texture: a normal one and a flipped one:

      MySprite
       |--Normal
       |--Flipped (scaled -1)
      

      Then, scale MySprite GameObject to -1 instead.

    2. Turn off backface culling in your shader.

      Just add Cull Off to the subshader. See also this.

      SubShader {
      
          Tags { "Queue"="Transparent" }
          Blend SrcAlpha OneMinusSrcAlpha
      
          Pass {
          Cull Off
          ...