您的位置:首页 > 移动开发 > Unity3D

Unity使用Shader控制物体材质的透明度(Lambert版和非光照版)

2015-06-23 15:21 567 查看
<pre name="code" class="cpp">Shader "Custom/MyShader_Two" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}  //接收的纹理
_TransVal ("Transparency Value", Range(0,1)) = 1  //透明度的值
_ColorTint("Shine(RGB)",color) = (1,1,1,1)//增强颜色
}
SubShader {
Tags { "RenderType"="Opaque" "Queue"="Transparent"}
CGPROGRAM
//声明使用兰伯特光照模型,并且最后会使用setcolor设置颜色
#pragma surface surf Lambert alpha  finalcolor:setcolor

//声明三种对应参数
sampler2D _MainTex;
float _TransVal;
float4 _ColorTint;
//输入参数
struct Input {
float2 uv_MainTex;
};
//声明颜色处理函数
void setcolor (Input IN, SurfaceOutput o, inout fixed4 color)
{
//将自选的颜色值乘给color
color *= _ColorTint;
}
//surf函数,处理部分
void surf (Input IN, inout SurfaceOutput o) {
half4 c = tex2D (_MainTex, IN.uv_MainTex);
o.Albedo = c.rgb;  //处理颜色
o.Alpha = c.a * _TransVal;//处理透明度
}
ENDCG
}
FallBack "Diffuse"
}




以上是使用光照模型情况下的shader,这种shader可以调整透明度,但是会接收光照,这次的需求是需要不接受光照的,于是我采用如下办法

<pre name="code" class="cpp">Shader "Custom/MyShader_Two" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
_Color("Color",Color) = (1,1,1,1)
}
SubShader {
Tags { "RenderType"="Queue" "Queue"="Transparent"} // "Queue"="Transparent"将其设置为透明,不然无法看见后面的东西(即使透明)
Blend SrcAlpha OneMinusSrcAlpha //实现Alpha的核心,使用语句进行Alpha混合
Pass {

CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

sampler _MainTex;
//float4 _MainTex_ST;  使用TRANSFORM_TEX必备
float4 _Color;

struct v2f {
float4 pos : POSITION;
float2 uv : TEXCOORD0;
float3 color : TEXCOORD1;
};

v2f vert(appdata_base v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
//TRANSFORM_TEX是在_MainTex_ST中的宏
//原始方法o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
//将uv贴图的坐标取出来
o.uv = v.texcoord;
//o.color = ShadeVertexLights(v.vertex, v.normal);取得法线贴图的光照
return o;
}

float4 frag(v2f i) : COLOR {
half4 c = tex2D(_MainTex, i.uv);
//在这个位置接收i.color的话可以接收光照
c.rgb = c.rgb * _Color;
return c*_Color;
}
ENDCG
}
}
FallBack "Diffuse"
}




这段代码有详细注释,如有错误,欢迎讨论。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity shader