这里使用一种更高效地从深度纹理中重建世界坐标的方法。

首先计算摄像机的视锥体的四条射线向量进行线性插值,插值后的值便是该像素在世界空间坐标下到摄像机的方向。

然后通过与深度值相乘即可得到摄像机位置到该像素的向量,加上摄像机的位置则是该像素在世界空间中的位置。

转载请注明出处:https://www.cnblogs.com/jietian331/p/9443343.html

c#代码:

 1 using UnityEngine;
 2 
 3 public class HighFog2 : PostEffectRenderer
 4 {
 5     [SerializeField]
 6     Color m_fogColor = Color.white;
 7     [Range(0f, 1f)]
 8     [SerializeField]
 9     float m_fogDensity = 0.9f;
10     [SerializeField]
11     float m_fogPosY = 0.1f;
12     [SerializeField]
13     float m_fogDisappearHeight = 8;
14 
15 
16     protected override string ShaderName
17     {
18         get { return "Custom/Study/HighFog2"; }
19     }
20 
21     protected override void OnRenderImage(RenderTexture src, RenderTexture dest)
22     {
23         float fov = base.SelfCamera.fieldOfView;
24         float near = base.SelfCamera.nearClipPlane;
25         Transform camT = base.SelfCamera.transform;
26 
27         float halfFOV = fov * Mathf.PI / 360f;
28         float toTopDis = near * Mathf.Tan(halfFOV);
29         float toRightDis = toTopDis * (Screen.width / Screen.height);
30         Vector3 toTop = camT.up * toTopDis;
31         Vector3 toRight = camT.right * toRightDis;
32         Vector3 toCenter = camT.forward * near;
33         Vector3 topLeft = (toCenter + toTop - toRight) / near;
34         Vector3 topRight = (toCenter + toTop + toRight) / near;
35         Vector3 bottomLeft = (toCenter - toTop - toRight) / near;
36         Vector3 bottomRight = (toCenter - toTop - toRight) / near;
37 
38         Matrix4x4 matrix = Matrix4x4.identity;
39         matrix.SetRow(0, bottomLeft);
40         matrix.SetRow(1, bottomRight);
41         matrix.SetRow(2, topLeft);
42         matrix.SetRow(3, topRight);
43 
44         base.Mat.SetMatrix("_CameraRays", matrix);
45         base.Mat.SetColor("_FogColor", m_fogColor);
46         base.Mat.SetFloat("_FogDensity", m_fogDensity);
47         base.Mat.SetFloat("_FogPosY", m_fogPosY);
48         base.Mat.SetFloat("_FogDisappearHeight", m_fogDisappearHeight);
49         base.OnRenderImage(src, dest);
50     }
51 }
View Code

相关文章: