屏幕后处理-运动模糊原理实例
using UnityEngine;

public class movemohu : MonoBehaviour {

    public Material mat;

    [Range(0.0f, 0.9f)]
    public float blurAmount = 0.5f;//与原图像混合的透明度

    private RenderTexture accumulationTexture;//上一次的渲染图

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (mat != null)
        {
            //当上一次的渲染图不存在或则说宽高都不一样了,说明重新开始场景了
            if (accumulationTexture == null || accumulationTexture.width != source.width || accumulationTexture.height != source.height)
            {
                accumulationTexture = new RenderTexture(source.width, source.height, 0);
                accumulationTexture.hideFlags = HideFlags.HideAndDontSave;

                Graphics.Blit(source, accumulationTexture);
            }

            //渲染纹理的恢复操作,发生在渲染的纹理时没有被清空的情况,这里需要和当前渲染的图像混合
            accumulationTexture.MarkRestoreExpected();
            mat.SetFloat("_BlurAmount", 1.0f - blurAmount);
            Graphics.Blit(source, accumulationTexture, mat);
            Graphics.Blit(accumulationTexture, destination);
        }
        else
        {
            Graphics.Blit(source, destination);
        }
    }

    private void OnDisable()
    {
        DestroyImmediate(accumulationTexture);
    }
}


Shader "Unlit/movemohu"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_BlurAmount("Blur Amount",Float) = 1.0
	}

	SubShader
	{
		Tags { "RenderType" = "Opaque" }
		LOD 100

		CGINCLUDE
		#include "UnityCG.cginc"
		sampler2D _MainTex;
		fixed _BlurAmount;

		struct v2f
		{
			float2 uv : TEXCOORD0;
			float4 vertex : SV_POSITION;
		};

		v2f vert(appdata_img v)
		{
			v2f o;
			o.vertex = UnityObjectToClipPos(v.vertex);
			o.uv = v.texcoord;
			return o;
		}

		fixed4 fragRGB(v2f i):SV_Target
		{
			return fixed4(tex2D(_MainTex,i.uv).rgb,_BlurAmount);
		}

		half4 fragA(v2f i) : SV_Target
		{
			return tex2D(_MainTex,i.uv);
		}
		ENDCG

		ZTest Always Cull Off ZWrite Off
		Pass
		{
			Blend SrcAlpha OneMinusSrcAlpha
			ColorMask RGB //不写入透明通道,但使用自定义的透明通道混合
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment fragRGB
			ENDCG
		}

		Pass 
		{
			Blend One Zero
			ColorMask A //写入原来的透明通道

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment fragA
			ENDCG
		}
	}
}



GIF.gif


首页 我的博客
粤ICP备17103704号