# 【三平面映射】

可以解决UV接缝不连续和缩放导致的拉伸显示异常。

下面是未使用(红色组)和使用了(蓝色组)的两组效果对比:

全屏显示

# Shader实现

Shader "vp/Triplanar"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _falloff("FallOff",float) = 1
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float3 worldPos :TEXCOORD0;
                float3 worldNormal:TEXCOORD1;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _falloff;
            inline float4 TriplanarSampling44(sampler2D topTexMap, float3 worldPos, float3 worldNormal, float falloff, float2 tiling)
            {
              float3 projNormal = (pow(abs(worldNormal), falloff));
              projNormal /= (projNormal.x + projNormal.y + projNormal.z) + 0.00001;
              float3 nsign = sign(worldNormal);
              half4 xNorm; half4 yNorm; half4 zNorm;
              xNorm = tex2D(topTexMap, tiling * worldPos.zy * float2(nsign.x, 1.0));
              yNorm = tex2D(topTexMap, tiling * worldPos.xz * float2(nsign.y, 1.0));
              zNorm = tex2D(topTexMap, tiling * worldPos.xy * float2(-nsign.z, 1.0));
              return xNorm * projNormal.x + yNorm * projNormal.y + zNorm * projNormal.z;
            }

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldPos = mul(v.vertex, unity_ObjectToWorld);
                o.worldNormal = mul(unity_WorldToObject, v.normal);

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                half4 col = TriplanarSampling44(_MainTex,i.worldPos,i.worldNormal,_falloff,_MainTex_ST.xy);
                return col;
            }
            ENDCG
        }
    }
}

参考自CSDN阿赵3d:三平面映射技术 (opens new window)