漫反射的计算公式:
float brigthness=dot(normal,lightDir)------法线和光线方向得到亮度
float3 pixelColor=brightness*lightColor*surfaceColor------表面像素最终的颜色
1、定义漫反射的变量,法线向量
struct appdata { float4 vertex : POSITION; float3 normal:Normal; }; struct v2f { float4 vertex : SV_POSITION; float3 worldNormal : TEXCOORD1; };
一个是对象空间坐标的法向量,另一个是世界空间坐标的法向量;
2、将对象空间坐标变换到世界空间坐标
v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); float3 worldNormal = UnityObjectToWorldNormal(v.normal); o.worldNormal = worldNormal; return o; }
3、片元着色器将其进行计算,输出最终的颜色
fixed4 frag (v2f i) : SV_Target { float3 normalDirection = normalize(i.worldNormal); float nl = max(0.0, dot(normalDirection, _WorldSpaceLightPos0.xyz)); float4 diffuseTerm = nl *_Color; return diffuseTerm; }
当然还可以添加贴图
完整代码如下:
Shader "Unlit/DiffuseShader" { Properties { _Color("Color",Color) = (1,0,0,1) _DiffuseTex("Texture",2D) = "white"{} _Ambient("Ambient",Range(0,1))=0.25 } SubShader { Tags { "RenderType" = "Opaque" "LightMode" = "ForwardBase"} LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" fixed4 _Color; sampler2D _DiffuseTex; float4 _DiffuseTex_ST; float _Ambient; struct appdata { float4 vertex : POSITION; float3 normal:Normal; float2 UV:TEXCOORD0; }; struct v2f { float4 vertex : SV_POSITION; float3 worldNormal : TEXCOORD1; float2 UV:TEXCOORD0; }; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); float3 worldNormal = UnityObjectToWorldNormal(v.normal); o.worldNormal = worldNormal; o.UV = TRANSFORM_TEX(v.UV, _DiffuseTex); return o; } fixed4 frag (v2f i) : SV_Target { float3 normalDirection = normalize(i.worldNormal); float4 tex = tex2D(_DiffuseTex, i.UV); float nl = max(_Ambient, dot(normalDirection, _WorldSpaceLightPos0.xyz)); float4 diffuseTerm = nl * tex*_Color; return diffuseTerm; } ENDCG } } }