Shader操作uv实现岩浆和河流效果

介绍

纹理贴图移动特效产生岩浆、瀑布效果实现原理是改变动态改变纹理坐标uv的值,使之移动

修改UV值来实现纹理贴图的滚动,其实就是让一个图片在滚来滚去,来模拟一些水流效果之类的。

这个效果其实在逻辑代码中也可以写,就是修改图片的坐标,不过在逻辑代码中的话需要两张图片来交替出现,而在 Shader中,因为 UV 坐标超过 1之后又会重新从 0 开始,所以只要一个Texture 就可以了。

代码j介绍

_MainTex 主纹理贴图

_MainTint 主要颜色

_ScrollXSpeed x轴移动速度

_ScrollYSpeed  y轴移动速度

主要是在surf函数里进行操作

fixed xScrollValue = _ScrollXSpeed * _Time;
fixed yScrollValue = _ScrollYSpeed * _Time;

x、y偏移量随时间增加

void surf (Input IN, inout SurfaceOutput o) {
fixed2 scrolledUV = IN.uv_MainTex;
fixed xScrollValue = _ScrollXSpeed * _Time;
fixed yScrollValue = _ScrollYSpeed * _Time;
scrolledUV += fixed2(xScrollValue, yScrollValue);
half4 c = tex2D (_MainTex, scrolledUV);
o.Albedo = c.rgb * _MainTint;
o.Alpha = c.a;
}

原理:

  • _Time是 unity shaderlab内置值
  • 这里用到了 Unity 提供的一个内置变量 _Time_Time 是一个 float4变量,值为 值为 Time (t/20, t, t2, t3), t 就是时间,就是说Unity给我们几个内定的时间速度来使用,默认是取X值。
  • 因为 _Time 一直在变化,所以 uv 也一直在变化,所以我们才能得到图片滚动的效果。
    • float4 _Time : Time (t/20, t, t2, t3)
      • 是一个四维向量
    • scrolledUV += fixed2(xScrollValue, yScrollValue);
      • uv的x,y值随时间累加偏移量
  • 最后整合uv与主颜色到当前纹理上,产生了这种移动的效果

运行图

demo_1_1.gif

完整代码

Shader "CookBookShaders/Scroll UV" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        //默认值就是白色
        
        _MainTint ("Diffuse Tint", Color) = (1, 1, 1, 1)
        _ScrollXSpeed ("XSpeed", Range (0, 100)) = 2  
        _ScrollYSpeed ("XSpeed", Range (0, 100)) = 2  
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200
        
        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;
        float _ScrollXSpeed;
        float _ScrollYSpeed;
        fixed4 _MainTint;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) 
        {
            //根据时间增加,修改 uv_MainTex ,例如从 (0,0) 到 (1,1) ,这样就类似于贴图在反方向运动。
            fixed2 scrolledUV = IN.uv_MainTex;

            fixed xScrollOffset = _ScrollXSpeed * _Time; 
            //注意_Time这个内置变量是float4 值为 Time (t/20, t, t*2, t*3), 
            //就是说Unity给我们几个内定的时间速度来使用,默认是取X值。
            fixed yScrollOffset = _ScrollYSpeed * _Time;

            scrolledUV += fixed2(xScrollOffset,yScrollOffset);

            half4 c = tex2D (_MainTex, scrolledUV);
            o.Albedo = c.rgb * _MainTint;
            o.Alpha = c.a;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}

参考链接

官方对 _Time 内置变量的说明

你可能感兴趣的:(Shader操作uv实现岩浆和河流效果)