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
  • 可以看出经过该公式计算后,我们的灯光强度在灯光距离限制处刚好为零
  • 这样就实现了额外灯的距离衰减效果了
相关推荐
虾球xz3 小时前
游戏引擎学习第114天
学习·游戏引擎
虾球xz4 小时前
游戏引擎学习第109天
学习·游戏引擎
心疼你的一切5 小时前
C# 中关于补位的写法 PadLeft,PadRight 函数
开发语言·unity·c#·游戏引擎·csdn·心疼你的一切
沐沐森的故事8 小时前
Unity for Python —— 强大的 Python 脚本支持提升 Unity 编辑器效率
python·unity·编辑器·pythonrunner·pythonengine
xklcy10 小时前
Unity通过Vosk实现离线语音识别方法
unity·语音识别
虾球xz13 小时前
游戏引擎学习第113天
学习·游戏引擎
老朱佩琪!1 天前
在Unity中用简单工厂模式模拟原神中的元素反应
unity·简单工厂模式
虾球xz1 天前
游戏引擎学习第111天
学习·游戏引擎
程序猿多布2 天前
预定义委托(C# and Unity)
unity·c#
虾球xz2 天前
游戏引擎学习第108天
学习·游戏引擎