UnityShader应用——水波效果

最近学了顶点片元Shader基本语法之后,决定拿一个Shader来分析一下,初学Shader,在此记录一下!

这个Shader效果都是在frag里进行;
   sampler2D _MainTex;
   float _WaveStrength;
   float _WaveFactor;
   float _TimeScale;
   
   fixed4 frag(v2f IN):COLOR
   {                
	//计算出fixed2(0.5,0.5)到uv每个点的单位向量及方向
      fixed2 uvDir = normalize(IN.uv-fixed2(0.5,0.5));
	//计算出fixed2(0.5,0.5)到uv每个点的距离
      fixed dis = distance(IN.uv,fixed2(0.5,0.5));   
      //加入uv偏移值   
      fixed2 uv = IN.uv+_WaveStrength*uvDir*sin(_Time.y*_TimeScale+dis*_WaveFactor);
      return tex2D(_MainTex, uv);
   }

UnityShader应用——水波效果_第1张图片
UnityShader应用——水波效果_第2张图片

  • Sin函数取值范围在(-1,1)之间;
  • _WaveStrength * uvDir控制偏移量的大小范围和方向;
  • Sin函数的变量为_Time.y,随着时间变化,Sin值会在(-1,1)之间变化,偏移量大小就会在(-_WaveStrength,WaveStrength)之间 变化;
效果图如下

Shader
Shader "Study/WaterWave1" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _WaveStrength("Wave Strength",Float) = 0.01
        _WaveFactor("Wave Factor",Float) = 50
        _TimeScale("Time Scale",Float) = 10
    }
    SubShader {
        
        Pass
        {
            CGPROGRAM

            #pragma vertex vert 
            #pragma fragment frag

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

            };

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

            sampler2D _MainTex;
            float _WaveStrength;
            float _WaveFactor;
            float _TimeScale;

            v2f vert (appdata v) 
            {
                v2f o;
                o.uv = v.uv;
                o.vertex = UnityObjectToClipPos(v.vertex);

                return o;
            }

            fixed4 frag(v2f IN):COLOR
            {                
				//计算出fixed2(0.5,0.5)到uv每个点的单位向量方向
                fixed2 uvDir = normalize(IN.uv-fixed2(0.5,0.5));
				//计算出fixed2(0.5,0.5)到uv每个点的距离
                fixed dis = distance(IN.uv,fixed2(0.5,0.5));

                fixed2 uv = IN.uv+_WaveStrength*uvDir*sin(_Time.y*_TimeScale+dis*_WaveFactor);
                return tex2D(_MainTex, uv);
            }
            ENDCG
        }

    } 
    FallBack "Diffuse"
}

你可能感兴趣的:(UnityShader)