Blur模糊其實(shí)理解了以后非常簡(jiǎn)單节仿。核心原理就是
1個(gè)點(diǎn)的顏色 并不用該點(diǎn)的顏色,而是用該點(diǎn)周?chē)悬c(diǎn)的均值
(1)確定取點(diǎn)范圍掉蔬, 例如周?chē)?個(gè)像素 或者周?chē)?0個(gè)像素
(2)確定各點(diǎn)權(quán)重廊宪,這也是高斯模糊的由來(lái),主要顏色分配的比重為正態(tài)分布女轿,即高斯分布箭启。
例子1:最簡(jiǎn)單的模糊
(1)新場(chǎng)景,plane上面放一張貼圖
(2)plane上的shader如下
Shader "Custom/ObjectBlur" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader
{
Tags{"Queue"="Transparent"}
pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
float uvOffset;
struct v2f {
float4pos : SV_POSITION;
float2uv : TEXCOORD0;
} ;
v2f vert (appdata_base v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
o.uv =TRANSFORM_TEX(v.texcoord,_MainTex);
return o;
}
float4 frag (v2f i) : COLOR
{
float4 s1 = tex2D(_MainTex,i.uv + float2(uvOffset,0.00));
float4 s2 = tex2D(_MainTex,i.uv + float2(-uvOffset,0.00));
float4 s3 = tex2D(_MainTex,i.uv + float2(0.00,uvOffset));
float4 s4 = tex2D(_MainTex,i.uv + float2(0.00,-uvOffset));
float4 texCol = tex2D(_MainTex,i.uv);
float4 outp;
float pct=0.2;
outp = texCol* (1- pct*4) + s1* pct + s2* pct+ s3* pct + s4* pct;
return outp;
}
ENDCG
}
}
}
以及BlurManager.cs腳本蛉迹,如下
using UnityEngine;
using System.Collections;
public class BlurManager : MonoBehaviour {
private float length =3f;
private float showTime = -100;
private float hideTime = -100;
void Update () {
if(showTime >0)
{
showTime -= Time.deltaTime;
Shader.SetGlobalFloat("uvOffset", (showTime/length) * 0.005f);
}
if(hideTime >0)
{
hideTime -= Time.deltaTime;
Shader.SetGlobalFloat("uvOffset", (1- hideTime/length) * 0.005f);
}
}
void OnGUI()
{
if(GUI.Button(new Rect(0,0,100,50),"Show"))
{
showTime = length;
}
if(GUI.Button(new Rect(100,0,100,50),"Hide"))
{
hideTime = length;
}
}
}
運(yùn)行后傅寡,點(diǎn)擊show按鈕,圖會(huì)從模糊變清晰,點(diǎn)擊hide按鈕會(huì)從清晰變模糊北救。
這基本是最簡(jiǎn)單的模糊了荐操,取本點(diǎn) 和其上下左右的4個(gè)偏移點(diǎn)。各點(diǎn)權(quán)重均為0.2珍策。uv偏移從0至0.005
效果如下圖還不錯(cuò)托启。
原圖
模糊后的效果