1.代码
Shader "Custom/VertColor1"
{
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 color : COLOR;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
if(o.vertex.x < 0.5){
o.color = float4(1,0,0,1);
}else{
o.color = float4(0,0,1,1);
}
return o;
}
fixed4 frag (v2f i) : SV_Target
{
return i.color;
}
ENDCG
}
}
}
效果:
2.裁剪坐标系
Shader "Custom/VertColor1"
{
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 color : COLOR;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.color = float4(o.vertex.x,0,0,1);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
return i.color;
}
ENDCG
}
}
}
效果:
3.世界坐标
绝对坐标,物体一动就失效了,一般不用。
Shader "Custom/VertColor1"
{
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 color : COLOR;
};
v2f vert (appdata v)
{
v2f o;
// 使用UNITY_MATRIX_M将模型空间顶点转换到世界空间
float4 worldPos = mul(UNITY_MATRIX_M, v.vertex);
if(length(worldPos.xy - float2(-5,-5)) < 1e-6){
o.color = float4(1,0,0,1);
}else if(length(worldPos.xy - float2(5,5)) < 1e-6){
o.color = float4(0,0,1,1);
}else if(length(worldPos.xy - float2(-5,5)) < 1e-6){
o.color = float4(0,1,1,1);
}else if(length(worldPos.xy - float2(5,-5)) < 1e-6){
o.color = float4(0,1,0,1);
}
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
return i.color;
}
ENDCG
}
}
}
效果: