效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cdb4d5865aac341bbeb797fa743221e8.png#pic_center)
代码
Shader "Custom/t1" {
Properties{
_Color ("Color", Color) = (1,1,1,1)
_Specular ("_Specular", Color) = (1,1,1,1)
_Gloss("Gloss", Range(2,200)) = 20
_MainTex ("MainTex", 2D) = "white" {}
}
SubShader{
Pass{
Tags{ "LightMode" = "ForwardBase" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Color;
sampler2D _MainTex;
float4 _MainTex_ST;
float _Gloss;
fixed4 _Specular;
struct a2v
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 texcoord : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float3 worldNormal : TEXCOORD0;
float3 worldPos : TEXCOORD1;
float2 uv : TEXCOORD2;
};
v2f vert (a2v a) {
v2f f;
f.pos = UnityObjectToClipPos(a.vertex);
f.worldNormal = mul( (float3x3) unity_ObjectToWorld, a.normal);
f.worldPos = mul(unity_ObjectToWorld, a.vertex).xyz;
f.uv = TRANSFORM_TEX (a.texcoord, _MainTex);
return f;
};
fixed4 frag ( v2f f) : SV_Target
{
fixed3 worldNormal = normalize ( f.worldNormal );
fixed3 worldLightDir = normalize ( UnityWorldSpaceLightDir ( f.worldPos ) );
fixed3 albedo = tex2D ( _MainTex, f.uv).rgb * _Color.rgb;
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
fixed3 diffuse = _LightColor0.rgb * albedo * max ( 0, dot(worldNormal, worldLightDir) );
fixed3 viewDir = normalize ( UnityWorldSpaceViewDir (f.worldPos) );
fixed3 halfDir = normalize ( worldLightDir + viewDir );
fixed3 specular = _LightColor0 * _Specular.rgb * pow (max (0, dot ( worldNormal, halfDir )) ,_Gloss);
return fixed4 (ambient + specular+ diffuse, 1);
};
ENDCG
}
}
FallBack "Diffuse"
}
原理:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/524c53616574344733908f0de6e24f41.png#pic_center)