《Unity Shader》 6.4.2 逐像素光照
(1)使用6.4.1节中使用的场景。
(2)新建一个材质。在本书资源中,该材质名为DiffusePixelLevelMat。


(3)新建一个Unity Shader。在本书资源中,该Shader名为Chapter6-DiffusePixelLevel。把新的Shader赋给第2步中创建的材质。

我知道为什么没有区别了,因为创建的就是标准光照模型。


(4)把第2步中创建的材质赋给胶囊体。


Chapter6-DiffusePixelLevel的代码和6.4.1小节中的非常相似,因此我们首先把6.4.1节中的代码直接粘贴到Chapter6-DiffusePixelLevel中,并进行如下修改。
(1)修改顶点着色器的输出结构体v2f:
(2)顶点着色器不需要计算光照模型,只需要把世界空间下的法线传递给片元着色器即可:
(3)片元着色器需要计算漫反射光照模型:
Shader "Custom/Chapter6-DiffuseFixelLevel"
{Properties{_Diffuse ("Diffuse", Color) = (1, 1, 1, 1)}SubShader{Tags {"LightMode"="ForwardBase"}Pass {CGPROGRAM#pragma vertex vert#pragma fragment frag#include "Lighting.cginc"fixed4 _Diffuse;struct a2v {float4 vertex : POSITION;float3 normal : NORMAL;};struct v2f {float4 pos : SV_POSITION;float3 worldNormal : TEXCOORD0;};v2f vert(a2v v) {v2f o;// Transform the vertex from object space to projection spaceo.pos = UnityObjectToClipPos(v.vertex);// Transform the normal from object space to world spaceo.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject); //用的左乘,使用顶点变换矩阵的逆转置矩阵对法线进行相同的变换 //normalize 向量单位化,使其长度为1return o;}fixed4 frag(v2f i) : SV_Target {// Get ambient termfixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;// Get the normal in world spacefixed3 worldNormal = normalize(i.worldNormal);// Get the light direction in world spacefixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);// Compute diffuse termfixed3 diffuse = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormal, worldLightDir));fixed3 color = ambient + diffuse;return fixed4(color, 1.0);}ENDCG}}Fallback "Diffuse"
}






