参考了WIKI:https://en.wikibooks.org/wiki/GLSL_Programming/Unity/Layers_of_Textures
先上图:
两张图片是根据lightDir与normal的夹角来确定混合权重的,所以放两张图:
下面是代码:
Shader "Custom/ShaderExample10"
{
Properties
{
_DecalTex ("Daytime Earth", 2D) = "white" {}
_MainTex ("Nighttime Earth", 2D) = "white" {}
_Color ("Nighttime Color Filter", Color) = (1,1,1,1)
}
SubShader
{
Pass
{
Tags {"LightMode" = "ForwardBase"}
GLSLPROGRAM
uniform sampler2D _MainTex;
uniform sampler2D _DecalTex;
uniform vec4 _Color;
uniform mat4 _Object2World;
uniform mat4 _World2Object;
uniform vec4 _WorldSpaceLightPos0;
uniform vec4 _LightColor0;
#ifdef VERTEX
//顶点着色器
out float levelOfLighting;
out vec4 textureCoordinates;
void main()
{
mat4 modelMatrix = _Object2World;
mat4 modelMatrixInverse = _World2Object;
vec3 normalDirection = normalize(vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));
vec3 lightDirection;
if (0.0 == _WorldSpaceLightPos0.w) //方向光
{
lightDirection = normalize(vec3(_WorldSpaceLightPos0));
}
else
{
lightDirection = vec3(0.0, 0.0, 0.0);
}
levelOfLighting = max(0.0, dot(normalDirection, lightDirection));
textureCoordinates = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
#endif
#ifdef FRAGMENT
//片元着色器
in float levelOfLighting;
in vec4 textureCoordinates;
void main()
{
vec4 nighttimeColor = _Color * texture2D(_MainTex, vec2(textureCoordinates));
vec4 daytimeColor = _LightColor0 * texture2D(_DecalTex, vec2(textureCoordinates));
gl_FragColor = mix(nighttimeColor, daytimeColor, levelOfLighting);
}
#endif
ENDGLSL
}
}
}