Version: 6000.3
语言: 中文
在URP的着色器中渲染其他光源
URP 中的通用附加光源数据组件

在URP中使用光衰减更改光源淡入淡出的方式

在您的场景场景包含游戏的环境和菜单。将每个唯一的场景文件视为一个独特的关卡。在每个场景中,你放置你的环境、障碍物和装饰品,基本上是将你的游戏设计和构建成碎片。更多信息
请参阅术语表
,你可以更改URP中的光照衰减函数,以实现实时和烘焙光照。

此示例将默认的URP光源衰减函数替换为二次衰减函数,该函数具有不同的视觉风格。你可以修改本页提到的函数,以实现其他视觉风格。二次光源衰减函数的行为与内置渲染管线获取场景内容并将其显示在屏幕上的一系列作。Unity 允许您从预构建的渲染管线中进行选择,或编写自己的渲染管线。更多信息
请参阅术语表
.

准备 URP 源代码以进行修改

此自定义需要修改 URP 源代码。有关说明,请参阅修改 URP 源代码

更改实时光源的光源衰减

要修改实时光源的光源衰减行为,请执行以下作:

  1. 打开以下 HLSL 文件:

    Packages/com.unity.render-pipelines.universal/ShaderLibrary/RealtimeLights.hlsl
    
  2. 修改DistanceAttenuation方法。 使用以下代码:

    // The quadratic falloff function provides a visual style
    // similar to the Built-In Render Pipeline light falloff.
    float DistanceAttenuation(float distanceSqr, float2 distanceAndSpotAttenuation)
    {
        // Calculate the linear distance from the squared distance value.
        float distance = sqrt(distanceSqr);
    
        // Calculate the range of the light by taking the inverse square root of the attenuation parameter.
        float range = rsqrt(distanceAndSpotAttenuation.x);
    
        // Normalize the distance to a value between 0 and 1 (1 at the source, 0 at the max range).
        float distance01 = saturate(1.0f - (distance / range));
    
        // Apply quadratic falloff.
        float lightAtten = pow(distance01, 2.0f);
    
        // Smooth the falloff across the entire range for a more gradual and natural fade.
        float smoothFactor = smoothstep(0.0f, 1.0f, distance01);
        lightAtten *= smoothFactor;
            
        return lightAtten;
    }
    
  3. 修改AngleAttenuation方法。 使用以下代码:

    float AngleAttenuation(float3 spotDirection, float3 lightDirection, float2 spotAttenuation)
    {
        // Compute the cosine of the angle between spotlight and surface.
        float SdotL = dot(spotDirection, lightDirection); 
    
        // Linearly interpolate attenuation between the inner and the outer cone.
        float atten = saturate(SdotL * spotAttenuation.x + spotAttenuation.y);
    
        // Apply cubic smoothing for a gradual edge falloff.
        atten = atten * atten * (3.0f - 2.0f * atten);
    
        return atten;
    }
    

下图比较了默认的URP光源衰减、本例中的自定义光源衰减函数以及内置渲染管线中的光源衰减。

A:URP默认衰减。B:内置渲染管线二次衰减。C:URP二次衰减(本例)
A:URP默认衰减。B:内置渲染管线二次衰减。C:URP二次衰减(本例)

更改烘焙灯光的光源衰减

为确保项目中烘焙光照的外观与实时光照的外观相匹配,请更改烘焙光源Mode属性设置为 Baked 的光源组件。Unity 在运行时之前预先计算烘焙光源的光照,并且不会将它们包含在任何运行时光照计算中。更多信息
请参阅术语表
.

  1. 打开以下文件:

    Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs
    
  2. lightData.falloffvalue 设置为 FalloffType.Legacy

    lightData.falloff = FalloffType.Legacy;
    

FalloffType.Legacy 使用二次衰减,与本例中的实时衰减匹配。你可以使用其他值来匹配项目中的实时光照。

有关更改烘焙光照中的光源衰减功能的更多信息,请参阅更改带衰减的光源的淡入淡出距离

其他资源

在URP的着色器中渲染其他光源
URP 中的通用附加光源数据组件