概述
把脚本 MyDepthOfField.cs 挂到main camera,注意前面的钩打上。
using UnityEngine;
using System.Collections;
public class MyDepthOfField : MonoBehaviour {
#region come from ImageEffectBase.cs
/// Provides a shader property that is set in the inspector
/// and a material instantiated from the shader
public Shader shader;
private Material m_Material;
void OnEnable() {
camera.depthTextureMode |= DepthTextureMode.Depth;
}
protected virtual void Start ()
{
// Disable if we don't support image effects
if (!SystemInfo.supportsImageEffects) {
enabled = false;
return;
}
// Disable the image effect if the shader can't
// run on the users graphics card
if (!shader || !shader.isSupported)
enabled = false;
}
protected Material material {
get {
if (m_Material == null) {
m_Material = new Material (shader);
//m_Material.hideFlags = HideFlags.HideAndDontSave;
m_Material.hideFlags = HideFlags.DontSave;
}
return m_Material;
}
}
protected virtual void OnDisable() {
if( m_Material ) {
//DestroyImmediate( m_Material );
Destroy( m_Material );
}
}
#endregion
void OnRenderImage (RenderTexture source, RenderTexture destination) {
//material.SetTexture ("_MainTex",source);
material.SetFloat("focalDistance01", 0.0f); // 0--1 , or near plane to far plane.
material.SetFloat("_OffsetDistance", 0.01f);
Graphics.Blit (source, destination, material);
}
}
把下面的shader拖到上面脚本的public参数中:
Shader "Custom/DoFShader" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
//Fog { Mode off }
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
//#pragma fragmentoption ARB_precision_hint_fastest
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform sampler2D _CameraDepthTexture;
uniform half _OffsetDistance;
uniform half focalDistance01;
fixed4 frag (v2f_img i) : COLOR
{
half blurFactor;
half4 I = tex2D(_MainTex, i.uv);
//fixed4 original = tex2D(_MainTex, i.uv);
half4 C = tex2D(_MainTex, i.uv);
C =tex2D(_MainTex,half2(i.uv.x+_OffsetDistance,i.uv.y+_OffsetDistance));
C+=tex2D(_MainTex,half2(i.uv.x+_OffsetDistance,i.uv.y-_OffsetDistance));
C+=tex2D(_MainTex,half2(i.uv.x-_OffsetDistance,i.uv.y+_OffsetDistance));
C+=tex2D(_MainTex,half2(i.uv.x-_OffsetDistance,i.uv.y-_OffsetDistance));
C+=tex2D(_MainTex,half2(i.uv.x+_OffsetDistance,i.uv.y));
C+=tex2D(_MainTex,half2(i.uv.x,i.uv.y+_OffsetDistance));
C+=tex2D(_MainTex,half2(i.uv.x-_OffsetDistance,i.uv.y));
C+=tex2D(_MainTex,half2(i.uv.x,i.uv.y-_OffsetDistance));
C*=0.125;
//return C;
float d = UNITY_SAMPLE_DEPTH ( tex2D (_CameraDepthTexture, i.uv) ); // i.uv.xy??
d = Linear01Depth (d);
blurFactor=saturate(abs(d-focalDistance01));
// blurFactor=saturate((IN.depth-_FocalDistance)*(IN.depth-_FocalDistance)*1.5);
// if(blurFactor<0.2)
// blurFactor*=blurFactor*3;
//return fixed4(blurFactor);
return lerp(I,C,blurFactor);
}
ENDCG
}
}
Fallback off
}
最后
以上就是辛勤世界为你收集整理的unity中景深(depth of field)的简单实现。。的全部内容,希望文章能够帮你解决unity中景深(depth of field)的简单实现。。所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复