屏幕渲染原图
特效处理后的图
场景渲染完成后 在 添加一些 特效
第一步 : 引擎 渲染完成后 最终的结果是 一张图片
第二步: 将 图片 传递给 shader 进行 二次计算
提示: C# 代码 必须挂在 Camera 上
Unity 目录机构如图:
![](https://i-blog.csdnimg.cn/blog_migrate/992faa81d60c842ad611559d2cff447b.jpeg)
第一步详解 :
C#脚本 代码
1. void OnRenderImage(RenderTextureFormat sourceTexture, RenderTextureFormat desTexture)
MonoBehaviour 生命周期中 的 OnRenderImage 回调
2. Graphics.Blit (sourceTexture,desTexture,mat);
sourceTexture : 拦截 相机渲染出来的图片
desTexture: 更改以后的图片 存在这里 重新交给引擎
mat : 用哪个 材质球 重新渲染 返回给 sourceTexture
void OnRenderImage(RenderTexture sourceTexture, RenderTexture desTexture)
{
Graphics.Blit(sourceTexture,desTexture,graphicMat);
}
第二步 详解:
简单高斯模糊 shader 代码
fixed4 frag (v2f i) : SV_Target
{
float2 tmpUV = i.uv;
fixed4 col = tex2D(_MainTex,tmpUV);
fixed4 col2 = tex2D(_MainTex,tmpUV+float2(-_Ambient,0));
fixed4 col3 = tex2D(_MainTex,tmpUV+float2(0,-_Ambient));
fixed4 col4 = tex2D(_MainTex,tmpUV+float2(_Ambient,0));
fixed4 col5 = tex2D(_MainTex,tmpUV+float2(0,_Ambient));
col = (col + col2+col3+col4+col5)/5.0;
return col;
}
第一步 完整 C# 源代码 贴上:
using UnityEngine;
using System.Collections;
public class CameMove : MonoBehaviour {
public Material graphicMat;
void OnRenderImage(RenderTexture sourceTexture, RenderTexture desTexture)
{
Graphics.Blit(sourceTexture,desTexture,graphicMat);
}
}
第二步 完整 Shader 源代码 贴上:
Shader "Custom/Gaoshi" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_Ambient("Ambient",float) = 0.001
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata {
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = v.uv;
return o;
}
float _Ambient;
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
float2 tmpUV = i.uv;
fixed4 col = tex2D(_MainTex,tmpUV);
fixed4 col2 = tex2D(_MainTex,tmpUV+float2(-_Ambient,0));
fixed4 col3 = tex2D(_MainTex,tmpUV+float2(0,-_Ambient));
fixed4 col4 = tex2D(_MainTex,tmpUV+float2(_Ambient,0));
fixed4 col5 = tex2D(_MainTex,tmpUV+float2(0,_Ambient));
col = (col + col2+col3+col4+col5)/5.0;
return col;
}
ENDCG
}
}
}