将不同的光照信息,如阳光,灯光保存在光照贴图的不同通道里,通过Shader利用这些信息进行处理,就可以动态为同一个场景调整不同的光照风格,而不用使用任何灯光。
通过c#脚本,我们可以动态修改效果:
public class ColorManager : MonoBehaviour { public Renderer[] renders; public Color DirLight = Color.white; public Color PointLight = Color.white; public Color AmbientColor = Color.white; // Use this for initialization void Start() { } // Update is called once per frame void Update() { for (int i = 0; i < renders.Length; i++) { for (int j = 0; j < renders[i].sharedMaterials.Length; j++) { renders[i].sharedMaterials[j].SetColor("_PointLight", PointLight); renders[i].sharedMaterials[j].SetColor("_ExColor", DirLight); renders[i].sharedMaterials[j].SetColor("_Ambient", AmbientColor); } } } }
通过Shader修改场景物体的渲染方式:
Shader "Unlit/LightMapShader" { Properties { _MainTex ("Texture", 2D) = "white" {} _ExColor("ExColor", Color) = (1,1,1,1) _PointLight("PointLight", Color) = (1,1,1,1) _Ambient("Ambient", Color) = (1,1,1,1) } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; float2 texcoord1 : TEXCOORD1; }; struct v2f { float2 uv : TEXCOORD0; UNITY_FOG_COORDS(1) float4 vertex : SV_POSITION; half2 uvLM : TEXCOORD1; }; sampler2D _MainTex; float4 _MainTex_ST; fixed4 _ExColor; fixed4 _PointLight; fixed4 _Ambient; v2f vert (appdata v) { v2f o; o.vertex = mul(UNITY_MATRIX_MVP, v.vertex); o.uv = TRANSFORM_TEX(v.uv, _MainTex); o.uvLM = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw; return o; } fixed4 frag (v2f i) : SV_Target { // sample the texture fixed4 col = tex2D(_MainTex, i.uv); fixed3 lm = DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, i.uvLM.xy)); col.rgb *= (lm.r * _ExColor + lm.g * _PointLight); col += _Ambient; return col; } ENDCG } } }
读取光照贴图信息并按我们想要的方式应用到最终渲染上。
col.rgb *= (lm.r * _ExColor + lm.g * _PointLight);烘培时,将直射光设置为(1,0,0),我们就能将直射光的光照强度和阴影信息保存到光照贴图的R通道。同理,将点灯光设置为(0,1,0),我们就能把点灯光的光照强度和阴影信息保存到光照贴图的G通道。最终我们就能将不同的光照信息动态混合,从而简单模拟动态光照效果,为同一个场景添加多种颜色风格。