【Unity渲染】自定义屏幕后处理

自定义屏幕后处理其实并不难,步骤分为两个部分,1.设置用于画面处理的材质球和Shader;2.在C#代码中使用OnrenderImage函数对摄像机画面进行处理。

1.创建Shader和材质球

使用ImageEffect(图像效果)类型的Shader。
Shader中要有名为_MainTex的主纹理,用来接收C#方法传入的屏幕图像。否则无法进行屏幕后处理。
将写好的shader赋值给材质球。
下面是一个简单地模糊shader。

Shader "Hidden/Image_Fuzzy"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Offset("Offset", Range(0, 0.05)) = 0.02

    }
    SubShader
    {
        // No culling or depth
        //Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

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

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

            sampler2D _MainTex;
            float _Offset;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                // just invert the colors
                //col.rgb = 1 - col.rgb;
            fixed4 c1 = tex2D(_MainTex, i.uv - (_Offset, 0));
            fixed4 c2 = tex2D(_MainTex, i.uv + (_Offset, 0));
            fixed4 c3 = tex2D(_MainTex, i.uv + (0, _Offset));
            fixed4 c4 = tex2D(_MainTex, i.uv - (0, _Offset));
            return( col + c1 + c2 + c3 + c4) / 5;;
            }
            ENDCG
        }
    }
}

2.调用C#中OnRenderImage方法

OnRenderImage后期处理效果。 在图像的所有渲染操作全部完成后调用。
该函数让您能够使用基于着色器的过滤器对最终图像进行处理,从而修改最终图像。 source 为传入的图像渲染纹理。destination为输出的结果纹理。
当摄像机附加了多个图像过滤器时, 它们按顺序依照下述方法对图像进行处理:将第一个过滤器的目标作为源传递给下一个过滤器,依此类推。


 Material material;

    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        // Copy the source Render Texture to the destination,
        // applying the material along the way.
        Graphics.Blit(source, destination, material);
    }

Graphics.Blit (Texture source, RenderTexture dest, Material mat, int pass= -1)函数

使用着色器将源纹理复制到目标渲染纹理。
source为输入的图像,对应shader中的_MainTex属性,填写OnRenderImage中的source即可。
dest为输出的图像,填写OnRenderImage中的destination即可。
mat为后处理使用的材质。

运行Unity即可看到后处理效果。

注意:1.带有OnRenderImage方法的屏幕后处理代码,需要挂到Camera组件上才可以。
2.Shader中要有名为_MainTex的主纹理,用来接收C#方法传入的屏幕图像。否则无法进行屏幕后处理。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

真鬼123

祝你节节高升岁岁平安越来越漂亮

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值