注:学习实践阶段,参考了unity shader 入门精要一书。
模糊效果
在进入慢速度状态时希望在视觉上呈现模糊效果,类似那种摄像机高速模糊,有残影的效果。
试了两种方案,都是基于后处理。一种采用不断叠加上一帧渲染纹理的方式,一种利用深度纹理重建世界坐标计算像素速度的方式进行渲染。但第二种方法的效果在该游戏上的效果并不适合,抖动太过剧烈。如图
而第一种实现的效果比较理想,如图(截图原因可能并不明显,仔细看能看到拖尾效果):
而且第一种方法实现更加简单,即利用一张渲染纹理来保存上一帧的处理结果,每一次处理通过将上一帧保存的渲染纹理和当前的渲染纹理进行混合叠加。
步骤
- 定义一个高斯模糊系数:
[Range(0.0f, 0.9f)]
ublic float blurAmount = 0.5f;
- 定义一个渲染纹理来保存前一帧混合纹理、
private RenderTexture accumulationTexture;
void OnDisable()
{
DestroyImmediate(accumulationTexture);//销毁
}
- 实现OnRenderImage函数:
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if(material != null)
{
if (accumulationTexture == null || accumulationTexture.width != source.width || accumulationTexture.height != source.height)
{
DestroyImmediate(accumulationTexture);
accumulationTexture = new RenderTexture(source.width, source.height, 0);
accumulationTexture.hideFlags = HideFlags.HideAndDontSave;
Graphics.Blit(source, accumulationTexture);
}
//避免沒有清空 RenderTexture 時 Unity 跳出警告
accumulationTexture.MarkRestoreExpected();
material.SetFloat("_BlurAmount", 1.0f - blurAmount);
Graphics.Blit (source, accumulationTexture, material,0);
Graphics.Blit (accumulationTexture, destination