如何在Unity中使用着色器弯曲对象?

时间:2018-10-26 12:48:59

标签: unity3d shader hlsl material vertex-shader

我有一个着色器脚本,可以用来弯曲世界。但是问题在于该脚本只能上下弯曲。如何添加以便可以左右移动?

// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject'

Shader "Custom/Bendy Diffuse - Radial" 
{
    Properties 
    {
        _Color ("Main Color", Color) = (1,1,1,1)
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _ReflectionColor ("Reflection Tint Color", Color) = (1,1,1,1)
    }

    SubShader 
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert vertex:vert addshadow
        #pragma multi_compile __ HORIZON_WAVES 
        #pragma multi_compile __ BEND_ON

        // Global properties to be set by BendControllerRadial script
        uniform half3 _CurveOrigin;
        uniform fixed3 _ReferenceDirection;
        uniform half _Curvature;
        uniform fixed3 _Scale;
        uniform half _FlatMargin;
        uniform half _HorizonWaveFrequency;

        // Per material properties
        sampler2D _MainTex;
        fixed4 _Color;
        fixed4 _ReflectionColor;

        struct Input 
        {
            float2 uv_MainTex;
        };

        half4 Bend(half4 v)
        {
            half4 wpos = mul (unity_ObjectToWorld, v);

            half2 xzDist = (wpos.xz - _CurveOrigin.xz) / _Scale.xz;

            half dist = length(xzDist);
            fixed waveMultiplier = 1;

            dist = max(0, dist - _FlatMargin);

            wpos.y -= dist * dist * _Curvature * waveMultiplier;

            wpos = mul (unity_WorldToObject, wpos);

            return wpos;
        }

        void vert (inout appdata_full v) 
        {
            #if defined(BEND_ON)
            v.vertex = Bend(v.vertex);  
            #endif
        }

        void surf (Input IN, inout SurfaceOutput o) 
        {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            o.Alpha = c.a;

            fixed4 detail = tex2D(_MainTex, IN.uv_MainTex);
            fixed4 refl = tex2D(_MainTex, IN.uv_MainTex);

            o.Albedo = detail.rgb * _Color.rgb;
            o.Alpha = 1;
            o.Emission = refl.rgb * _ReflectionColor.rgb;
        }
        ENDCG

    }

    Fallback "Mobile/Specular/Diffuse"
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则您正在尝试制造弯曲地球的幻觉。您有xzDist,将这个向量乘以未修改的Y。因此,基本上,如果它是从原点离开的,请将其向左弯曲。较高的点将更远离中心弯曲,赤道以下的点可能会弯曲到中心。无法保证这看起来会正确。