核心
物体边缘 = 视角方向与顶点法线垂直
Shader "Unlit/019"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Diffuse ("漫反射", Color) = (1,1,1,1)
_RimColor("边缘光", Color) = (1,1,1,1)
_RimPower("边缘光强度",Range(0,3)) =1
}
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;
fixed4 _RimColor;
float _RimPower;
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);
//视角方向
fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
//漫反射光=入射光线强度*纹素值*材质的漫反射系数* 映射值为正数(表面法线方向 · 光源方向)
fixed3 diffuse = _LightColor0.rgb * albedo * _Diffuse.rgb * (dot(worldLightDir,i.worldNormal)*0.5+0.5);
//边缘光
float rim = 1-dot(i.worldNormal,viewDir);
fixed3 rimColor = _RimColor * pow(rim,1/_RimPower);
//环境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
fixed3 color = ambient + diffuse + rimColor;
return fixed4(color,1);
}
ENDCG
}
}
}
网友评论