Unity中URP下计算额外灯的方向

文章目录


前言

在上一篇文章中,我们获取了URP下额外灯的数据。

在这篇文章中,我们用获取到的数据来计算额外灯的方向。


一、为什么额外灯的方向,不像主平行灯一样直接获取?

1、主平行灯

  • 对于模型的每一个顶点来说,无论顶点位置在哪?我们主平行灯的方向都是不会改变的
  • 我们使用的是,模型顶点指向主平行灯,他们的方向也是一致的

2、额外灯中,包含 点光源、聚光灯 和 平行灯

  • 点光源 和 聚光灯

对于这两种额外灯类型来说:

照射到模型每一个顶点上,额外灯的方向是不一致的,都需要单独计算

我们使用的是模型顶点指向 额外灯

  • 平行灯
    和主平行光实例图一样

二、获得模型顶点指向额外灯的单位向量

  • 在这里Unity没有使用normalise函数归一化,而是使用了原始的方法
  • 模型顶点指向额外光:
  • l i g h t V e c t o r = l i g h t P o s i t i o n W S − p o s i t i o n W S lightVector = lightPositionWS - positionWS lightVector=lightPositionWS−positionWS
  • 向量归一化:
  • l i g h t D i r e c t i o n = l i g h t V e c t o r ∣ l i g h t V e c t o r ∣ = l i g h t V e c t o r 1 l i g h t V e c t o r ⋅ l i g h t V e c t o r lightDirection = \frac{lightVector}{\lvert lightVector\rvert}=lightVector\frac{1}{\sqrt{lightVector·lightVector}} lightDirection=∣lightVector∣lightVector=lightVectorlightVector⋅lightVector 1

三、Unity中的实现

  • 计算得到顶点指向额外灯的方向
  • lightPositionWS.w:代表额外灯类型(平行光=0,点灯=1)

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

  • 防止 点积 出现零在分母的情况,对其取了一个最大值

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

  • 最后,带入公式: l i g h t D i r e c t i o n = l i g h t V e c t o r ∣ l i g h t V e c t o r ∣ lightDirection = \frac{lightVector}{\lvert lightVector\rvert} lightDirection=∣lightVector∣lightVector,得到额外灯方向单位向量

half3 lightDirection = half3(lightVector * rsqrt(distanceSqr));

相关推荐
WiChP5 小时前
【V0.1B16】从零开始的2D游戏引擎开发之路
开发语言·算法·游戏引擎
百里香酚兰6 小时前
【Unity学习笔记】如何把粉色Prefab还原
笔记·学习·unity
xcLeigh8 小时前
Unity基础:使用Transform控制物体旋转——Rotate与LookAt详解
unity·教程·transform·rotate·lookat
平行云10 小时前
3D应用推流太贵太慢?ImmerShare Lite:利用本地算力实现极简一键分享
unity·ue5·实时云渲染·云桌面·像素流·云游戏·串流
淡海水11 小时前
11-04-Unity-Span-foreach-LINQ的分配与热路径边界
unity·c#·linq·foreach·span
狂人开飞机20 小时前
23、实战平台跳跃游戏
游戏·游戏引擎·godot
灸木1 天前
Unity 多线程与并发:什么时候该用多线程?
unity
淡海水1 天前
11-02-Unity-Mono-vs-IL2CPP-两种脚本后端的数据结构行为差异
数据结构·unity·游戏引擎·il2cpp·mono
彧azz1 天前
初学Unity:编辑器
笔记·学习·unity·游戏引擎