Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Unity Shaders and Effects Cookbook(4-1、4-2):靜態立方體貼圖的建立與使用

編輯:關於 Android 開發

Unity Shaders and Effects Cookbook(4-1、4-2):靜態 Cubemap 的建立與使用

開始學習第 4 章「著色器的反射」。看完前兩節,來做個記錄——反射主要利用的是 Cubemap 立方體貼圖。

認識 Cubemap

立方體貼圖,顧名思義就是在一個立方體上貼了 6 張圖。可以這樣假想:在一間艷麗的房間裡,有一顆表面如鏡的球,球面上就反射了房間裡的所有景物,像一個大號的凸面鏡。

這是網上找的一張圖,很直觀地表達了這個意思。

注意標題說的是靜態立方體貼圖。之所以叫靜態,是因為這裡用的立方體貼圖是事先生成好的圖片,而非動態生成的。這意味著:以上圖場景為例,若是靜態貼圖,那麼當球移動時,球面上顯示的內容不會變動;而現實中球一移動,反射出的畫面理應隨之改變。此處先用靜態貼圖來學習 Cubemap 知識,後面(書中 4.6 節)才會學到動態立方體貼圖。

建立 Cubemap

首先在 Assets 中右鍵新建一個 Cubemap。接著搭建場景,加入一個 Sphere 作為 Camera 的容器,因為要借助 Camera 的 API 來生成 Cubemap。

下面是我搭建的場景:

接著編寫一個 Unity 編輯器外掛來生成 CubeMap:

using UnityEngine; using System.Collections; using UnityEditor; public class GenerateStaticCubemap : ScriptableWizard { public Transform renderPosition; public Cubemap cubemap; void OnWizardUpdate() { helpString = "Select transform to render from and cubemap to render into"; isValid = (renderPosition != null && cubemap != null); } void OnWizardCreate() { GameObject go = new GameObject("CubemapCamera", typeof(Camera)); go.transform.position = renderPosition.position; go.transform.rotation = Quaternion.identity; go.camera.RenderToCubemap(cubemap); DestroyImmediate(go); } [MenuItem("CookBookShaders/Render Cubemap")] static void RenderCubemap() { ScriptableWizard.DisplayWizard("Render Cube", typeof(GenerateStaticCubemap), "Render"); } }

由於是編輯器工具,要遵循 Unity 的規範,把這個程式碼檔放在名為 Editor 的文件夾中(自己新建即可)。核心就是 go.camera.RenderToCubemap(cubemap);——借助 Camera 的 API 生成 Cubemap,然後用 [MenuItem("CookBookShaders/Render Cubemap")] 添加一個菜單作為入口。

等 Unity 編譯完成後,菜單欄就會出現我們自訂的菜單:

把剛才建立的 Cubemap 與 Sphere 拖進來,點擊 Render 就生成了 Cubemap。

使用 Cubemap

建立好立方體貼圖後就能使用了。同樣建立一個材質與一個 Shader,Shader 程式碼如下:

Shader "CookBookShaders/Cubemap" { Properties { _MainTint("Diffuse Tint",Color)=(1,1,1,1) _MainTex ("Base (RGB)", 2D) = "white" {} _Cubemap("Cubemap",CUBE)=""{} _ReflectionAmount("Reflection Amount",Range(0.01,1))=0.5 } SubShader { Tags { "RenderType"="Opaque" } LOD 200 CGPROGRAM #pragma surface surf Lambert float4 _MainTint; sampler2D _MainTex; samplerCUBE _Cubemap; float _ReflectionAmount; struct Input { float2 uv_MainTex; float3 worldRefl; }; void surf (Input IN, inout SurfaceOutput o) { half4 c = tex2D (_MainTex, IN.uv_MainTex)*_MainTint; o.Emission=texCUBE(_Cubemap,IN.worldRefl).rgb *_ReflectionAmount; o.Albedo = c.rgb; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }

幾個重點:在 Properties 塊中,立方體貼圖的類型是 CUBE(普通紋理是 2D);在 SubShader 中,定義變數時要用 samplerCUBE(普通紋理是 sampler2D);在 Input 結構體中使用了 Unity 內建變數 worldRefl,它提供了著色器中使用的世界反射向量;最後在 surf 函數中用 texCUBE 從 Cubemap 取紋素:texCUBE(_Cubemap,IN.worldRefl).rgb。

運行後的效果:

示例工程下載:https://pan.baidu.com/s/1qYcNKxI

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved