需求一:使用双Pass渲染,将两张图片以好看的顺序渲染至平面上。并且使用扭曲效果,让背景随时间产生位移
思路:两个Pass做背面剔除,并返回颜色效果,其中一个Pass根据时间变化对UV进行变换实现扭曲效果,一个Pass直接返回颜色-->图片本身的样子
效果:
code:
Shader "Unlit/Follow4"
{
Properties{
_MainTex("Main Texture", 2D) = "white"{}
_SecTex("Second Texture", 2D) = "white" {}
_DisplacementTex("Displacement Texture", 2D) = "white"{}
_Magnitude("Magnitude", Range(0, 1)) = 0
}
SubShader
{
CGINCLUDE
//声明类型
sampler2D _MainTex;
sampler2D _SecTex;
sampler2D _DisplacementTex;
float _Magnitude;
//获取模型数据
struct appdata
{
float4 vertex : POSITION;
float2 uv: TEXCOORD0;
};
//存放计算结果
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv: TEXCOORD1;
};
//数据给FS
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
ENDCG
//渲染类型,适用于透明通道
Tags { "RenderType"="Transparent" }
LOD 100
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
Cull Back
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
// FS阶段
fixed4 frag (v2f i) : SV_Target
{
float2 disuv = float2(i.uv.x+_Time.x*2, i.uv.y+_Time.x*2);
fixed4 col = tex2D(_MainTex, i.uv);
float2 dis = tex2D(_DisplacementTex,disuv).xy;
dis = ((dis*2)-1)*_Magnitude;
//distortion
float4 tex_color = tex2D(_MainTex, i.uv + dis);
return tex_color;
}
//pass结束:没有报错
ENDCG
}
pass
{
Blend SrcAlpha OneMinusSrcAlpha
Cull Back
ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 frag(v2f i):SV_Target
{
float4 color = tex2D(_SecTex,i.uv);
return color;
}
ENDCG
}
}
}
需求二; 用替换渲染分别渲染两个不同渲染模式的平面
思路:为两个GameObject添加两个Material,定义为不同的渲染模式。在Shader声明两个SubShader定义不同的通道,返回颜色值,再通过代码对不同通道的Material赋予不同的贴图。
效果:
Shader "Unlit/Follow2"
{
Properties
{
_MainTexture ("MainTexture", 2D) = "white" {}
_SecTexture("SecTexture", 2D) = "white"{}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTexture;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTexture, i.uv);
return col;
}
ENDCG
}
}
SubShader
{
Tags { "RenderType"="Transparent" }
LOD 100
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _SecTexture;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_SecTexture, i.uv);
return col;
}
ENDCG
}
}