学习传送门:
blog 推介:
unity shader 的入门学习
凯尔八阿哥:Unity&Shader基础篇-“HelloCg”
Shader Forge
cg 方法:
https://developer.download.nvidia.cn/CgTutorial/cg_tutorial_appendix_e.html
Unity 内置结构体参考:
Unity>Editor>Data>CGInclude>UnityCG.cginc
要在代码中使用这些内置结构体一定要添加命令#include “UnityCG.cginc”
1.图片按高度局部隐藏
先上最终效果图
图片透明处理方式1(Discarding Transparent Fragments)
关键字:discard(cutoff)
缺点:片段着色器读取RGBA贴图并与用户指定的范围值大小比较alpha值。如果 alpha值比范围值小,就丢弃着色片段使之透明。注意: 这项指令在某些平台上是非常缓慢的,特别是在移动设备上。因此,混合(blending)通常更有效。
Shader "Cg texturing with alpha discard" {
Properties {
_MainTex ("RGBA Texture Image", 2D) = "white" {}
_Cutoff ("Alpha Cutoff", Float) = 0.5
}
SubShader {
Pass {
Cull Off // since the front is partially transparent,
// we shouldn't cull the back
//注意: 内容要写在cg 语法中
CGPROGRAM
//名称可定义顶点shder入口
#pragma vertex vert
//片元着色入口
#pragma fragment frag
uniform sampler2D _MainTex;
uniform float _Cutoff;
//自定义 数据结构
struct vertexInput {
//语义绑定 : COLOR
float4 vertex : POSITION;
float4 texcoord : TEXCOORD0;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 tex : TEXCOORD0;
};
vertexOutput vert(vertexInput input)
{
vertexOutput output;
output.tex = input.texcoord;
output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
return output;
}
float4 frag(vertexOutput input) : COLOR
{
float4 textureColor = tex2D(_MainTex, input.tex.xy);
if (textureColor.a < _Cutoff)
// alpha value less than user-specified threshold?
{
discard; // yes: discard this fragment
}
return textureColor;
}
ENDCG
}
}
// The definition of a fallback shader should be commented out
// during development:
// Fallback "Unlit/Transparent Cutout"
}
图片透明处里方式2 混合(blending)
关键字:Transparency
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
// Transparency blending
Blend SrcAlpha OneMinusSrcAlpha
}
最终版:简易shader 效果 (图片按高度局部隐藏)
Shader "szw/HidePart"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
//0-1f
posy("Pos Y", float) = 0
_Cutoff ("Alpha Cutoff", Float) = 0.5
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
// Transparency blending
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
float posy;
sampler2D _MainTex;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
fixed4 color : COLOR;
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
// get vertex
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : COLOR
{
fixed4 col = tex2D(_MainTex, i.uv);
// > up to down < down to up
// (i.uv.y i.vertex.y
if (i.uv.y < posy)
{
col.a = 0;
}
else
{
col.rgb = col.rgb;
}
return col;
}
ENDCG
}
}
}
代码调用shader中的属性
//"_Color" shader 中定义的属性名称
material.SetColor("_Color",new Color(1,0,0,1));
问题记录
1.scene 场景和游戏场景 高度不一致, game视图高度值是scene 视图的2倍才会生效。
解决方案:
将 if (i.vertex.y < posy)改写为 if (i.uv.y < posy)即可 ,这样更好,按图片
2.不希望在顶层绘制的话
将ZTest Always注释掉