Unity中URP下额外灯的距离衰减

文章目录


前言

在上一篇文章中,我们分析了额外灯的方向怎么计算。

在这篇文章中,我们来分析一下额外灯的距离衰减。


一、额外灯的距离衰减

  • 在上一篇文章中,完成了额外灯方向计算后,来到了计算额外光的衰减部分
  • 衰减包括:距离衰减 和 角度衰减
  • 我们这篇文章主要分析 距离衰减

DistanceAttenuation(distanceSqr, distanceAndSpotAttenuation.xy)

二、DistanceAttenuation函数的传入参数

  • 调用

DistanceAttenuation1(distanceSqr, distanceAndSpotAttenuation.xy)

1、distanceSqr

  • 这个计算光线向量后的点积结果

// Directional lights store direction in lightPosition.xyz and have .w set to 0.0.

// This way the following code will work for both directional and punctual lights.

float3 lightVector = lightPositionWS.xyz - positionWS * lightPositionWS.w;

float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN);

2、distanceAndSpotAttenuation

  • 该参数是通过内置变量获取的
  • 该参数是通过C#脚本提前计算好的

3、_AdditionalLightsAttenuation

  • 我们来看一下C#是怎么计算得出该参数的


  • 衰减默认值(平行光)

  • k_DefaultLightAttenuation,默认值为(0,0,0,1)

  • 非平行光下,会对衰减值进行修改

  • 该函数对衰减值,做出了修改。使衰减值在灯光限制处刚好为0

4、GetPunctualLightDistanceAttenuation函数

该函数为以下参数做出准备:

  • Unity使灯光限制处为0的公式:
  • s m o o t h F a c t o r = l i g h t R a n g e S q r − d i s t a n c e T o L i g h t S q r l i g h t R a n g e S q r − f a d e S t a r t D i s t a n c e S q r smoothFactor=\frac{lightRangeSqr - distanceToLightSqr}{lightRangeSqr -fadeStartDistanceSqr} smoothFactor=lightRangeSqr−fadeStartDistanceSqrlightRangeSqr−distanceToLightSqr

我们来看一下该公式实现了什么

  • l i g h t R a n g e S q r = l i g h t R a n g e ∗ l i g h t R a n g e lightRangeSqr = lightRange * lightRange lightRangeSqr=lightRange∗lightRange
  • f a d e S t a r t D i s t a n c e S q r = 0.8 f ∗ 0.8 f ∗ l i g h t R a n g e S q r ; fadeStartDistanceSqr = 0.8f * 0.8f * lightRangeSqr; fadeStartDistanceSqr=0.8f∗0.8f∗lightRangeSqr;(0.8指的是80%开始衰减)
  • d i s t a n c e T o L i g h t S q r :灯光的衰减距离的平方 distanceToLightSqr:灯光的衰减距离的平方 distanceToLightSqr:灯光的衰减距离的平方

三、DistanceAttenuation函数的程序体

  • s m o o t h F a c t o r = l i g h t R a n g e S q r − d i s t a n c e T o L i g h t S q r l i g h t R a n g e S q r − f a d e S t a r t D i s t a n c e S q r smoothFactor=\frac{lightRangeSqr - distanceToLightSqr}{lightRangeSqr -fadeStartDistanceSqr} smoothFactor=lightRangeSqr−fadeStartDistanceSqrlightRangeSqr−distanceToLightSqr
  • 可以看出经过该公式计算后,我们的灯光强度在灯光距离限制处刚好为零
  • 这样就实现了额外灯的距离衰减效果了
相关推荐
程序猿多布7 小时前
预定义委托(C# and Unity)
unity·c#
虾球xz10 小时前
游戏引擎学习第108天
学习·游戏引擎
虾球xz11 小时前
游戏引擎学习第112天
java·学习·游戏引擎
Edision_li16 小时前
DeepSeek教unity------Dotween
unity·游戏引擎
zfoo-framework17 小时前
Unity中NavMesh的使用 及其 导出给java服务端进行寻路
unity
程序猿多布18 小时前
数学函数(C#、Lua 、Unity)
unity·c#·lua
虾球xz19 小时前
游戏引擎学习第110天
数码相机·学习·游戏引擎
爱写代码的山山1 天前
虚幻蓝图解决抗锯齿方案
游戏·ue5·游戏引擎·虚幻·抗锯齿化
github_czy1 天前
(9/100)每日小游戏平台系列
javascript·python·游戏引擎·游戏程序
头发掉光的程序员1 天前
正顺基碱基
c++·算法·游戏引擎·图形渲染