// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld'
Shader "Custom/SingleTexture"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(8.0,256)) = 20
_Specular ("Specular", Color) = (1,1,1,1)
}
SubShader
{
//_LightColor0只有定义了"LightMode" = "ForwardBase"才正确
Tags { "RenderType"="Opaque" "LightMode" = "ForwardBase"}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "Lighting.cginc"
fixed4 _Color;
sampler2D _MainTex;
float4 _MainTex_ST;
float _Glossiness;
fixed4 _Specular;
struct a2v
{
float4 vertex:POSITION; //顶点坐标
float3 normal:NORMAL; //顶点法线
float4 texcoord:TEXCOORD0; //第一组纹理坐标
};
struct v2f
{
float4 pos:SV_POSITION; //裁剪空间的位置,顶点着色器必做的操作,把顶点从模型空间转换到裁剪空间
float4 worldPos:TEXCOORD0;//世界坐标,用于计算光照
float3 worldNormal:TEXCOORD1;//世界法线,用于计算光照
float2 uv:TEXCOORD2;//采样得到的UV值
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex); //模型坐标转到裁剪坐标
o.worldPos = mul(unity_ObjectToWorld,v.vertex); //得到世界坐标
o.worldNormal = UnityObjectToWorldNormal(v.normal); //得到世界法线量
o.uv = TRANSFORM_TEX(v.texcoord,_MainTex); //对顶点的纹理坐标转换得到最终的UV值
return o;
}
fixed4 frag(v2f i):SV_Target
{
fixed3 worldNormal = normalize(i.worldNormal);//计算出归一化的世界法线
fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));//归一化的从点到光源的方向
fixed3 abedo = tex2D(_MainTex,i.uv).rgb * _Color.rgb;//本身的颜色
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;//环境光
fixed3 halfLambert = dot(worldNormal,worldLightDir) * 0.5 + 0.5;//半兰伯特模型
fixed3 diffuse = _LightColor0.rgb * abedo * halfLambert;//漫反射颜色
fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));//从该点到相机的方向
fixed3 halfDir = normalize(worldLightDir + viewDir);//Phong模型
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0,dot(worldNormal,halfDir)),_Glossiness);//高光反射
return fixed4(ambient + diffuse + specular,1);//最终颜色
}
ENDCG
}
}
FallBack "Specular"
}
一开始没有定义Tags { "RenderType"="Opaque" "LightMode" = "ForwardBase"} 导致效果不对一直不对,定义了才好了。