兩種方式表現(xiàn)出來的效果相同
Shader "Unlit/019"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Diffuse ("漫反射", Color) = (1,1,1,1)
_Steps("顏色階級", Range(1,30)) = 1
_ToonEffect("卡通效果", Range(0,1) ) = 0.5
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
//引入光照
#include "Lighting.cginc"
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
fixed3 worldNormal : TEXCOORD1;
float3 worldPos : TEXCOORD2;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Diffuse;
float _Steps;
float _ToonEffect;
v2f vert (appdata_base v)
{
v2f o;
//頂點位置
o.vertex = UnityObjectToClipPos(v.vertex);
//法線方向
o.worldNormal = UnityObjectToWorldNormal(v.normal);
//世界坐標
o.worldPos = mul(unity_ObjectToWorld,v.vertex);
//紋理坐標縮放偏移
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// 紋理采樣
fixed4 albedo = tex2D(_MainTex, i.uv);
//光源方向
fixed3 worldLightDir = UnityWorldSpaceLightDir (i.worldPos);
//半蘭伯特模型=映射值為正數(shù)(表面法線方向 · 光源方向)
float difLight = dot(worldLightDir,i.worldNormal)*0.5+0.5;
//顏色平滑在【0嗅钻,1】之間
difLight = smoothstep(0,1,difLight);
//顏色離散化
float toon = floor(difLight * _Steps) / _Steps;
difLight = lerp(difLight,toon,_ToonEffect);
//漫反射光=入射光線強度*紋素值*材質(zhì)的漫反射系數(shù)*半蘭伯特模型
fixed3 diffuse = _LightColor0.rgb * albedo * _Diffuse.rgb * difLight;
//環(huán)境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 color = ambient + diffuse;
return fixed4(color,1);
}
ENDCG
}
}
}
Shader "Unlit/019"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Diffuse ("漫反射", Color) = (1,1,1,1)
_RampTex("漸進紋理",2D)="while"{}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
//引入光照
#include "Lighting.cginc"
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
fixed3 worldNormal : TEXCOORD1;
float3 worldPos : TEXCOORD2;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Diffuse;
sampler2D _RampTex;
v2f vert (appdata_base v)
{
v2f o;
//頂點位置
o.vertex = UnityObjectToClipPos(v.vertex);
//法線方向
o.worldNormal = UnityObjectToWorldNormal(v.normal);
//世界坐標
o.worldPos = mul(unity_ObjectToWorld,v.vertex);
//紋理坐標縮放偏移
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// 紋理采樣
fixed4 albedo = tex2D(_MainTex, i.uv);
//光源方向
fixed3 worldLightDir = UnityWorldSpaceLightDir (i.worldPos);
//半蘭伯特模型=映射值為正數(shù)(表面法線方向 · 光源方向)
float difLight = dot(worldLightDir,i.worldNormal)*0.5+0.5;
//漸進紋理采樣
fixed4 rampColor = tex2D(_RampTex, fixed2(difLight,difLight));
//漫反射光=入射光線強度*紋素值*材質(zhì)的漫反射系數(shù)*漸進紋理
fixed3 diffuse = _LightColor0.rgb * albedo * _Diffuse.rgb * rampColor;
//環(huán)境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 color = ambient + diffuse;
return fixed4(color,1);
}
ENDCG
}
}
}