C#代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JingShen : MonoBehaviour {
public Material mat;
[Range(0f, 100f)]
public float focalDistance = 10;//焦点距离
[Range(0, 100)]
public float nearBlurScale = 0;//近距离模糊缩放
[Range(0,1000f)]
public float farBlurScale = 50;//远距离模糊缩放
public int downSample = 1;//分辨率降低值
public int sampleScale = 1;//采样半径
private void OnEnable()
{
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;//开启深度
}
private void OnDisable()
{
GetComponent<Camera>().depthTextureMode &= ~DepthTextureMode.Depth;//关闭深度
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Mathf.Clamp(focalDistance, transform.GetComponent<Camera>().nearClipPlane, transform.GetComponent<Camera>().farClipPlane);//限制焦点距离在摄像机最近裁剪面和最远裁剪面
RenderTexture temp1 = RenderTexture.GetTemporary(source.width >> downSample, source.height >> downSample, 0, source.format);//降低分辨率
RenderTexture temp2 = RenderTexture.GetTemporary(source.width >> downSample, source.height >> downSample, 0, source.format);
Graphics.Blit(source, temp1);
mat.SetVector("_offset", new Vector4(0, sampleScale, 0, 0));//垂直取值
Graphics.Blit(temp1, temp2, mat,0);
mat.SetVector("_offset", new Vector4(sampleScale, 0, 0, 0));//水平取值
Graphics.Blit(temp2, temp1, mat,0);
mat.SetTexture("_BlurTex", temp1);
mat.SetFloat("_focalDistance", FocalDistance(focalDistance));
mat.SetFloat("_nearBlurScale", nearBlurScale);
mat.SetFloat("_farBlurScale", farBlurScale);
Graphics.Blit(source, destination, mat, 1);
RenderTexture.ReleaseTemporary(temp1);