《Unity Shader》6.4.3 半兰伯特模型

(1)仍然使用6.4.1小节中使用的场景。
(2)新建一个材质。在本书资源中,该材质名为HalfLambertMat。

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

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

打开Chapter6-HalfLambert,删除已有的Shader代码,把6.4.2小节的Chapter6-DiffusePixelLevel代码粘贴进去,并使用半兰伯特公式修改片元着色器中计算漫反射光照的部分:

java 复制代码
Shader "Custom/Chapter6-HalfLambert"
{
    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  space
                o.pos  =  UnityObjectToClipPos(v.vertex);
                
                // Transform  the  normal  from  object  space  to  world  space
                o.worldNormal  =  mul(v.normal,  (float3x3)unity_WorldToObject); //用的左乘,使用顶点变换矩阵的逆转置矩阵对法线进行相同的变换 //normalize 向量单位化,使其长度为1
            
                return  o;
            }

            fixed4  frag(v2f  i)  :  SV_Target  {
                //  Get  ambient  term
                fixed3  ambient  =  UNITY_LIGHTMODEL_AMBIENT.xyz;
                //  Get  the  normal  in  world  space
                fixed3  worldNormal  =  normalize(i.worldNormal);
                //  Get  the  light  direction  in  world  space
                fixed3  worldLightDir  =  normalize(_WorldSpaceLightPos0.xyz);
                 //  Compute  diffuse  term
                fixed  halfLambert  =  dot(worldNormal,  worldLightDir) * 0.5  +  0.5;
                fixed3   diffuse   =   _LightColor0.rgb * _Diffuse.rgb * halfLambert;

                fixed3 color  =  ambient  +  diffuse;

                return  fixed4(color,  1.0);
            }

            

            ENDCG

        }
    }
    Fallback  "Diffuse"
}
相关推荐
HonestGoat10 小时前
Unity3d之碰撞体设置
unity
那个村的李富贵17 小时前
Unity自适应文本提示框:从原理到实战
unity·游戏引擎
HonestGoat18 小时前
Unity3d之鼠标光标
unity
WarPigs18 小时前
Unity人物翻越功能
unity·游戏引擎
游乐码18 小时前
Unity基础(四)向量相关
游戏·unity·游戏引擎
VT LI20 小时前
Cocos2d-x 引擎架构全面深度解析:从底层渲染到上层交互的系统性技术全景
游戏引擎·cocos·引擎架构
Kurisu57521 小时前
探灵直播2026最新官方正版免费下载 一键转存 永久更新 (看到速转存 资源随时走丢)
游戏·游戏引擎·游戏程序·动画·关卡设计
神码编程21 小时前
【Unity】MiniGame编辑器小游戏(十五)中国象棋局域网对战【Chinese Chess】(上)
unity·编辑器·游戏引擎·小游戏
伽蓝_游戏21 小时前
第四章:AssetBundle 核心机制与文件结构
unity·c#·游戏引擎·游戏程序
郝学胜-神的一滴1 天前
中级OpenGL教程 006:高光反射原理与 Shader 实现
c++·unity·godot·图形渲染·three.js·opengl·unreal