Shader实例:Planar Reflection 平面反射

本文介绍了Unity中实现平面反射的Shader应用,通过代码MirrorReflection.cs展示并详细注解,包括反射矩阵和歪截头体矩阵的使用。此技术适用于创建镜面和水面等反射效果,附带可运行的UnityPackage供进一步研究。
摘要由CSDN通过智能技术生成

目前采用比较多的反射,最终效果示例:
在这里插入图片描述
代码已经中文注解,有2部分需扩展:反射矩阵、歪截头体矩阵。注解中有来源链接可以去理解推导过程。
可用于镜面和水面。

咱还是直接看注解过的代码
MirrorReflection.cs

using UnityEngine;
using System.Collections;
using UnityEditor;

[ExecuteInEditMode]
public class MirrorReflection : MonoBehaviour
{
	//public Material m_matCopyDepth;
	// 为效率,禁用像素级光
	public bool m_DisablePixelLights = true;
	public int m_TextureSize = 256;
	// 微调,获得更准确反射
	public float m_ClipPlaneOffset = 0.07f;
	// 参与反射的layer
	public LayerMask m_ReflectLayers = -1;

	private Hashtable m_ReflectionCameras = new Hashtable(); // Camera -> Camera table

	public RenderTexture m_ReflectionTexture = null;
	//public RenderTexture m_ReflectionDepthTexture = null;
	private int m_OldReflectionTextureSize = 0;

	private static bool s_InsideRendering = false;

	// 渲染摄像机
	public Camera m_Camera;

	// 即将渲染
	public void OnWillRenderObject()
	{
		if (!enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled)
			return;

		Camera cam = Camera.current;

		if (!cam)
			return;

		if (cam != m_Camera )
			return;

		// Safeguard from recursive reflections.
		// 本过程不支持打断
		if (s_InsideRendering)
			return;
		s_InsideRendering = true;

		// 创建反射摄像机、渲染纹理
		Camera reflectionCamera;
		CreateMirrorObjects(cam, out reflectionCamera);

		// find out the reflection plane: position and normal in world space
		// 反射平面
		Vector3 pos = transform.position;
		Vector3 normal = transform.up;

		// Optionally disable pixel lights for reflection
		// 像素级光设为无效
		int oldPixelLightCount = QualitySettings.pixelLightCount;
		if (m_DisablePixelLights)
			QualitySettings.pixelLightCount = 0;

		// 从cam克隆出反射摄像机fov什么的
		UpdateCameraModes(cam, reflectionCamera);

		// Render reflection
		// Reflect camera around reflection plane
		// 通过offset调整过的反射面
		float d = -Vector3.Dot(normal, pos) - m_ClipPlaneOffset;
        Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);

		// 使用反射屏幕得到反射矩阵
		Matrix4x4 reflection = Matrix4x4.zero;
		CalculateReflectionMatrix(ref ref
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好热哦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值