Unity图形学之Shader2.0 Blurning
1.屏幕后期特效:场景渲染完以后 在 添加一些特效
(1)引擎 渲染后最终的结构 是一张图片:OnRenderImage是脚本生命周期函数
Graphics.Blit(sourceTexture, desTexture, graphicsMat);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
graphicsMat = new Material(myShader);
}
// Update is called once per frame
void Update()
{
}
public Shader myShader;
private Material graphicsMat;
//sourceTexture 相机在整个场景渲染完后传递给我们的图片 desTexture 更改以后得图片 存在这里,重新交给引擎重新渲染
void OnRenderImage(RenderTexture sourceTexture, RenderTexture desTexture) {
//指定一个Material 去渲染拦截的图片sourceTexture,最终输出新的desTexture
Graphics.Blit(sourceTexture, desTexture, graphicsMat);
}
}
(2)将图片 传递给 shader 进行 二次计算:
Shader "Hidden/GaoSi"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Ambient("Ambient",float) = 0.001
}
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;
};
float _Ambient;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
float2 tempUV = i.uv;
//float ambient = _Ambient;
fixed4 col = tex2D(_MainTex, tempUV);
fixed4 col2 = tex2D(_MainTex, tempUV+float2(-_Ambient,0));
fixed4 col3 = tex2D(_MainTex, tempUV+float2(0,-_Ambient));
fixed4 col4 = tex2D(_MainTex, tempUV+float2(_Ambient,0));
fixed4 col5 = tex2D(_MainTex, tempUV+float2(0,_Ambient));
col = (col+col2+col3+col4+col5) / 5.0;
// just invert the colors
//col.rgb = 1 - col.rgb;
return col;
}
ENDCG
}
}
}