Unity shader学习之简单的水效果

效果如下:

 

代码如下:

Shader "Custom/Study/Water"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Texture", 2D) = "white" {}
        _NormalMap ("Normal", 2D) = "bump" {}
        _Distortion ("Distortion", Range(1, 100)) = 10
        _WaveSpeed ("Wave speed", Vector) = (0,0,0,0)
        _ReflectRate ("Reflect Rate", Range(0,1)) = 0.7
    }

    SubShader
    {
        Tags
        {
            "RenderType" = "Transparent"
            "Queue" = "Transparent"
        }

        GrabPass { "_GrabTex" }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            
            #include "UnityCG.cginc"

            float4 _Color;
            sampler2D _MainTex;
            float4 _MainTex_ST;
            sampler2D _NormalMap;
            float4 _NormalMap_ST;
            sampler2D _GrabTex;
            float4 _GrabTex_TexelSize;
            float _Distortion;
            float4 _WaveSpeed;
            float _ReflectRate;


            struct appdata
            {
                float4 vertex : POSITION;
                float4 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float4 uv : TEXCOORD0;
                float4 scrPos : TEXCOORD1;
            };

            
            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv.xy = TRANSFORM_TEX(v.uv, _MainTex);
                o.uv.zw = TRANSFORM_TEX(v.uv, _NormalMap);
                o.scrPos = ComputeGrabScreenPos(o.pos);
                return o;
            }
            
            fixed4 frag (v2f i) : SV_Target
            {
                float2 speedNormal = _Time.y * _WaveSpeed.xy;
                float2 speedMainTex = _Time.y * _WaveSpeed.zw;

                fixed3 normal1 = UnpackNormal(tex2D(_NormalMap, i.uv.zw + speedNormal));
                fixed3 normal2 = UnpackNormal(tex2D(_NormalMap, i.uv.zw - speedNormal));
                fixed3 normal = normalize(normal1 + normal2);

                float2 offset = normal.xy * _GrabTex_TexelSize.xy * _Distortion;

                fixed4 mainTex = tex2D(_MainTex, i.uv.xy + speedMainTex + offset);
                mainTex *= _Color;

                float2 grabUV = (i.scrPos.xy + offset) / i.scrPos.w;
                fixed4 grabTex = tex2D(_GrabTex, grabUV);
                
                fixed4 col = lerp(mainTex, grabTex, _ReflectRate);
                return col;
            }
            ENDCG
        }
    }

    Fallback Off
}

 

shader面板如下:

转载请注明出处:https://www.cnblogs.com/jietian331/p/14080732.html

 

 关于 GrabPass:

 

 详见:https://zhuanlan.zhihu.com/p/83507625

 

posted @ 2020-12-03 15:48  孤独の巡礼  阅读(2104)  评论(0编辑  收藏  举报