从哪里开始创建二维水?

时间:2018-12-12 15:25:42

标签: unity3d

我想在Unity引擎中创建2d水。您能接受我的建议,从哪里开始?这是2d水https://www.youtube.com/watch?v=iBWwNHEHo3I的示例。谢谢前进

1 个答案:

答案 0 :(得分:1)

一种方法是使用利用GrabPass的着色器。您需要在水所在的位置制作一个四边形,然后将带有着色器的材质应用于四边形。着色器应具有GrabPass,然后具有垂直翻转和扭曲GrabPass的通道。这样的着色器的一个示例如下(source):

Shader "Custom/WaterGrab" 
{
    Properties 
    {        
        _Colour ("Colour", Color) = (1,1,1,1)
        _MainTex ("Noise text", 2D) = "bump" {}
        _Magnitude ("Magnitude", Range(0,1)) = 0.05
    }

    SubShader
    {
        Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque"}
        ZWrite On Lighting Off Cull Off Fog { Mode Off } Blend One Zero

        GrabPass { "_GrabTexture" }

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

            sampler2D _GrabTexture;
            fixed4 _Colour;
            sampler2D _MainTex;
            float  _Magnitude;

            struct vin
            {
                float4 vertex : POSITION;
                float4 color : COLOR;
                float2 texcoord : TEXCOORD0;

            };

            struct v2f
            {
                float4 vertex : POSITION;
                fixed4 color : COLOR;
                float2 texcoord : TEXCOORD0;
                float4 uvgrab : TEXCOORD1;

            };

            float4 _MainTex_ST;

            // Vertex function 
            v2f vert (vin v)
            {
                v2f o;
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                o.color = v.color;
                o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);


            #if UNITY_UV_STARTS_AT_TOP
                float scale = -1.0;
            #else
                float scale = 1.0;
            #endif            

                o.uvgrab.xy = (float2(o.vertex.x, (o.vertex.y)* scale) + o.vertex.w) * 0.5;
                o.uvgrab.zw = o.vertex.zw;

                float4 top = mul(UNITY_MATRIX_MVP, float4(0, 0.5, 0, 1));
                top.xy /= top.w;

                o.uvgrab.y = 1 - (o.uvgrab.y + top.y);

                return o;
            }

            // Fragment function
            half4 frag (v2f i) : COLOR
            {        

                half4 bump = tex2D(_MainTex, i.texcoord );
                half2 distortion = UnpackNormal(bump).rg;


                i.uvgrab.xy += distortion * _Magnitude;                    
                fixed4 col = tex2D( _GrabTexture, i.uvgrab);                
                return col * _Colour;
            }

            ENDCG
        } 
    }
}

在这样的着色器中,您需要提供凹凸图,以告诉水如何使GrabPass变形。在上面的示例中,应将其作为_MainTex纹理插入。它看起来应该像这样: enter image description here