要点
1) 阴影投射一般直接引用unity自带的,比如: FallBack "VertexLit" FallBack "Transparent/Cutout/VertexLit" //针对半透明物体的情况 里面都包含名叫ShadowCaster的Pass来处理阴影投射 2) 接收阴影只需要用3个宏加几行代码就行了 SHADOW_COORDS(texIndex) TRANSFER_SHADOW(appdata) SHADOW_ATTENUATION(v2f)
主贴图漫反射(MainTex)+高光反射+阴影投射+接收阴影
Shader "My/Light/Shadow_CastAndRecv" { Properties { _MainTex("Main Tex", 2D) = "white" {} _Color("Diffuse Color", Color) = (1, 1, 1, 1) _Specular("Specular", Color) = (1, 1, 1, 1) //高光反射颜色 _Gloss("Gloss", Range(8.0, 256)) = 20 //高光区域大小 } SubShader { Pass { Tags { "LightMode" = "ForwardBase" } CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma multi_compile_fwdbase #include "Lighting.cginc" #include "AutoLight.cginc" struct appdata { float4 vertex : POSITION; float3 normal : NORMAL; //顶点法线 float2 texcoord : TEXCOORD0; }; struct v2f { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; float3 worldNormal : TEXCOORD1; float3 worldPos: TEXCOORD2; SHADOW_COORDS(3) }; sampler2D _MainTex; float4 _MainTex_ST; fixed4 _Color; fixed _Cutoff; fixed4 _Specular; float _Gloss; v2f vert(appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.worldNormal = UnityObjectToWorldNormal(v.normal); o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz; o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); TRANSFER_SHADOW(o); return o; } fixed4 frag(v2f i) : SV_Target { fixed3 worldNormal = normalize(i.worldNormal); fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos)); //光方向(世界空间) fixed4 texColor = tex2D(_MainTex, i.uv); fixed3 albedo = texColor.rgb * _Color.rgb; //取贴图颜色作为漫反射颜色 fixed3 ambientColor = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo; //环境光 fixed3 lambert = max(0, dot(worldNormal, worldLightDir)); //表面法线和光线方向夹角的cos值成正比 fixed3 diffuseColor = _LightColor0.rgb * albedo * lambert; //漫反射计算公式 fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos)); //顶点到相机的观察方向向量 fixed3 halfDir = normalize(worldLightDir + viewDir); // blinn模型引入的h向量 fixed3 specularColor = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss); // blinn模型高光反射计算公式(更亮, 高光区域更大) //fixed atten = 1.0; //衰减 //fixed shadow = SHADOW_ATTENUATION(i); //接收阴影 //atten *= showdow; UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos); //光照衰减+接收阴影宏 return fixed4(ambientColor + (diffuseColor + specularColor) * atten, 1); } ENDCG } } FallBack "VertexLit" //引用它的ShadowCaster的Pass }
标签:MainTex,Color,Shader,fixed3,worldNormal,CH9,SHADOW,阴影 From: https://www.cnblogs.com/sailJs/p/17083575.html