(转)【风宇冲】Unity3D教程宝典之Blur

时间:2023-03-10 05:35:08
(转)【风宇冲】Unity3D教程宝典之Blur

原创文章如需转载请注明:转载自风宇冲Unity3D教程学院

                Blur
Blur模糊其实理解了以后非常简单。核心原理就是 1个点的颜色 并不用该点的颜色,而是用该点周围所有点的均值 (1)确定取点范围, 例如周围3个像素 或者周围10个像素 (2)确定各点权重,这也是高斯模糊的由来,主要颜色分配的比重为正态分布,即高斯分布。
例子1:最简单的模糊 (1)新场景,plane上面放一张贴图 (2)plane上的shader如下
  1. Shader "Custom/ObjectBlur" {
  2. Properties {
  3. _MainTex ("Base (RGB)", 2D) = "white" {}
  4. }
  5. SubShader
  6. {
  7. Tags{"Queue"="Transparent"}
  8. pass
  9. {
  10. CGPROGRAM
  11. #pragma vertex vert
  12. #pragma fragment frag
  13. #include "UnityCG.cginc"
  14. sampler2D _MainTex;
  15. float4 _MainTex_ST;
  16. float uvOffset;
  17. struct v2f {
  18. float4  pos : SV_POSITION;
  19. float2  uv : TEXCOORD0;
  20. } ;
  21. v2f vert (appdata_base v)
  22. {
  23. v2f o;
  24. o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
  25. o.uv =  TRANSFORM_TEX(v.texcoord,_MainTex);
  26. return o;
  27. }
  28. float4 frag (v2f i) : COLOR
  29. {
  30. float4 s1 = tex2D(_MainTex,i.uv + float2(uvOffset,0.00));
  31. float4 s2 = tex2D(_MainTex,i.uv + float2(-uvOffset,0.00));
  32. float4 s3 = tex2D(_MainTex,i.uv + float2(0.00,uvOffset));
  33. float4 s4 = tex2D(_MainTex,i.uv + float2(0.00,-uvOffset));
  34. float4 texCol = tex2D(_MainTex,i.uv);
  35. float4 outp;
  36. float pct=0.2;
  37. outp = texCol* (1- pct*4) + s1* pct + s2* pct+ s3* pct + s4* pct;
  38. return outp;
  39. }
  40. ENDCG
  41. }
  42. }
  43. }

以及BlurManager.cs脚本,如下

  1. using UnityEngine;
  2. using System.Collections;
  3. public class BlurManager : MonoBehaviour {
  4. private float length =3f;
  5. private float showTime = -100;
  6. private float hideTime = -100;
  7. void Update () {
  8. if(showTime >0)
  9. {
  10. showTime -= Time.deltaTime;
  11. Shader.SetGlobalFloat("uvOffset", (showTime/length) * 0.005f);
  12. }
  13. if(hideTime >0)
  14. {
  15. hideTime -= Time.deltaTime;
  16. Shader.SetGlobalFloat("uvOffset", (1- hideTime/length) * 0.005f);
  17. }
  18. }
  19. void OnGUI()
  20. {
  21. if(GUI.Button(new Rect(0,0,100,50),"Show"))
  22. {
  23. showTime = length;
  24. }
  25. if(GUI.Button(new Rect(100,0,100,50),"Hide"))
  26. {
  27. hideTime = length;
  28. }
  29. }
  30. }

运行后,点击show按钮,图会从模糊变清晰,点击hide按钮会从清晰变模糊。 这基本是最简单的模糊了,取本点 和其上下左右的4个偏移点。各点权重均为0.2。uv偏移从0至0.005 效果如下图还不错。
原图 (转)【风宇冲】Unity3D教程宝典之Blur
模糊后的效果 (转)【风宇冲】Unity3D教程宝典之Blur
参考文章