Unity Shader系列文章:Unity Shader目錄-初級篇
Unity Shader系列文章:Unity Shader目錄-中級篇
效果:

鏡子效果
原理:
通過將攝像機的渲染結(jié)果實時更新到渲染紋理中,翻轉(zhuǎn)渲染紋理顯示。
1. 創(chuàng)建渲染紋理, Create >RenderTexture;
2. 將RenderTexture拖入Camera中,攝像機的渲染結(jié)果實時更新到渲染紋理;
3. 編寫shader代碼,創(chuàng)建材質(zhì),將RenderTexture拖到材質(zhì)上。

RenderTexture拖入Camera中

RenderTexture拖到材質(zhì)上
shader代碼:
// 鏡子效果
Shader "Custom/Mirror"
{
Properties
{
_MainTex ("Main Tex", 2D) = "white" { } // 渲染紋理
}
SubShader
{
Tags { "RenderType" = "Opaque" "Queue" = "Geometry" }
pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
// _MainTex_ST(聲明方式:name_ST): 聲明_MainTex是一張采樣圖,用于uv運算, 下面2個是等價的
// o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);
// o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
// 如果沒有聲明是不能進行TRANSFORM_TEX的運算的。_MainTex_ST.xy為紋理圖Tiling(縮放), zw為紋理中的offset(偏移)
// 如果Tiling 和 Offset留的是默認值,即Tiling為(1,1) Offset為(0,0)的時候,可以不用TRANSFORM_TEX運算
// 即:o.uv = v.texcoord
float4 _MainTex_ST;
// 應(yīng)用傳遞給頂點著色器的數(shù)據(jù)
struct a2v
{
float4 vertex: POSITION; // 語義:模型空間下的頂點坐標
float4 texcoord: TEXCOORD0; // 語義:模型第一組紋理坐標
};
// 頂點傳遞給片元著色器的數(shù)據(jù)
struct v2f
{
float4 pos: SV_POSITION; // 語義:裁剪空間下的頂點坐標
float2 uv: TEXCOORD0;
};
// 頂點著色器函數(shù)
v2f vert(a2v v)
{
v2f o;
// 將頂點坐標從模型空間變換到裁剪空間
// 等價于o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.pos = UnityObjectToClipPos(v.vertex);
// 計算紋理坐標(縮放和平移)
// 等價于o.uv = v.texcoord * _MainTex_ST.xy + _MainTex_ST.zw;
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
// 紋理X翻轉(zhuǎn),因為鏡子里圖像是左右相反的
o.uv.x = 1 - o.uv.x;
return o;
}
// 片元著色器函數(shù)
fixed4 frag(v2f i): SV_TARGET
{
// 對主紋理采樣
fixed4 color = tex2D(_MainTex, i.uv);
return color;
}
ENDCG
}
}
Fallback "Off"
}