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));

相关推荐
雪下的新火1 天前
Blender:法线图&黑白图
游戏·unity·游戏引擎·blender·笔记分享
HahaGiver6661 天前
从0到1做一个“字母拼词”Unity小游戏(含源码/GIF)- 实现多单词顺序通关进度逻辑
unity·游戏引擎·游戏程序
Dr.勿忘2 天前
Unity一分钟思路---UI任务条:宝箱位置如何准确卡在百分比位置上
ui·unity·游戏程序·屏幕适配
weixin_424294672 天前
Unity 实现 ScrollBar 值变化控制 Panel 位置的方法
unity·游戏引擎
在路上看风景2 天前
## 2.2 状态同步
unity
霜绛2 天前
Unity:lua热更新(一)——AB包AssetBundle、Lua语法
笔记·学习·游戏·unity·lua
霜绛2 天前
Unity:lua热更新(二)——Lua语法(续)
笔记·学习·unity·游戏引擎·lua
yi碗汤园2 天前
【一文了解】C#反射
开发语言·unity·c#
HahaGiver6662 天前
Unity Shader Graph 3D 实例 - 基础的模型贴图渲染
3d·unity·游戏程序·贴图·游戏美术
HahaGiver6662 天前
Unity Shader Graph 3D 实例 - 一个简单的3D打印效果
3d·unity·游戏引擎