2

如何使用自定义标准表面着色器将值动画化为目标值?

例如:

...
float targetAlpha; //Set by the property block, or a C# script
float currrentAlpha; //Used internally only.

void surf (Input IN, inout SurfaceOutputStandard o)
{
    currrentAlpha = lerp(currrentAlpha, targetAlpha, unity_DeltaTime.x);

    o.Alpha = currrentAlpha;
}

此代码不起作用,但应该演示目标是什么:设置 targetAlpha 时,着色器将淡入该值。

4

2 回答 2

3

有几种方法可以做到这一点。其中之一是使用内置着色器变量:

    Shader "Custom/Test" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _TargetAlpha ("TargetAlpha", Range(0, 1)) = 0.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows alpha:fade

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Alpha;
        fixed4 _Color;
        half _TargetAlpha;


        void surf (Input IN, inout SurfaceOutputStandard o) 
        {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Alpha = lerp(o.Alpha, _TargetAlpha, clamp(_SinTime.w, 0, 1));
        }
        ENDCG
    }
    FallBack "Diffuse"
 }
于 2018-05-19T23:19:58.617 回答
3

上面答案中的着色器在 Unity 2018.2 中仍然有效。然而,_SinTime在 -1 和 1 之间波动,而我们希望范围在 0 和 1 之间。代码clamp(_SinTime.w, 0, 1)钳制在所需的值上,但是 alpha 保持为零的时间过长。所以我们需要绝对值,像这样:abs(_SinTime.w).

修改后的着色器:

    Shader "Custom/Test" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _TargetAlpha ("TargetAlpha", Range(0, 1)) = 0.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows alpha:fade

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        half _Alpha;
        fixed4 _Color;
        half _TargetAlpha;


        void surf (Input IN, inout SurfaceOutputStandard o) 
        {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Alpha = lerp(o.Alpha, _TargetAlpha, abs(_SinTime.w));
        }
        ENDCG
    }
    FallBack "Diffuse"
 }
于 2019-10-16T06:28:12.030 回答