首页 > 解决方案 > 如何在 Unity 中使用着色器弯曲对象?

问题描述

我有一个着色器脚本,我用它来弯曲世界。但问题是这个脚本只能上下弯曲。如何添加才能左右两边?

// 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"
}

标签: unity3dshaderhlslvertex-shader

解决方案


如果我正确理解了您的问题,那么您正在尝试制造弯曲地球的错觉。你有xzDist,加上这个向量乘以未修改的Y。所以基本上如果它从原点离开,把它向左弯曲。高的点会更远离中心弯曲,赤道以下的点可能会弯曲到中心。不能保证这看起来是正确的。


推荐阅读