[Unity] 2D Sprite Billboard Shader 出现意料之外的白边的解决方法

372 阅读1分钟

一开始我是照抄的 en.wikibooks.org/wiki/Cg_Pro…

Shader "2D/Billboard" {
    Properties{
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
        _ScaleX("Scale X", Float) = 1.0
        _ScaleY("Scale Y", Float) = 1.0
    }
    SubShader{
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }
        
        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass {
            CGPROGRAM

            #pragma vertex vert  
            #pragma fragment frag

            // User-specified uniforms            
            uniform sampler2D _MainTex;
            uniform float _ScaleX;
            uniform float _ScaleY;
            uniform float _VerticalBillboarding;

            struct a2v
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;  
            };

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


            v2f vert(a2v v)
            {
                v2f o;

                o.pos = mul(UNITY_MATRIX_P,
                    mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))
                    + float4(v.vertex.x, v.vertex.y, 0.0, 0.0)
                    * float4(_ScaleX, _ScaleY, 1.0, 1.0));

                o.uv = v.uv;

                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }

            ENDCG
        }
    }
}

后来发现有些图片是正常的,有些图片出现了白边

我就想干脆直接全抄 unity

Unity 默认 shader:

github.com/TwoTailsGam…

github.com/TwoTailsGam…

关键的部分在于我把 UnitySprites.cginc 中的顶点部分改成了

inline float4 Billboard(float4 vertex)
{
    return mul(UNITY_MATRIX_P,
        mul(UNITY_MATRIX_MV, float4(0.0, 0.0, 0.0, 1.0))
        + float4(vertex.x, vertex.y, 0.0, 0.0)
        * float4(_ScaleX, _ScaleY, 1.0, 1.0));
}

v2f SpriteVert(appdata_t IN)
{
    v2f OUT;

    UNITY_SETUP_INSTANCE_ID(IN);
    UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);

    OUT.vertex = UnityFlipSprite(IN.vertex, _Flip);
    OUT.vertex = Billboard(OUT.vertex);
    OUT.texcoord = IN.texcoord;
    OUT.color = IN.color * _Color * _RendererColor;

#ifdef PIXELSNAP_ON
    OUT.vertex = UnityPixelSnap(OUT.vertex);
#endif

    return OUT;
}

shader 放在 github.com/CheapMeow/U…

我还在相似的问题上回复了hhh answers.unity.com/questions/9…