歡迎您光臨本站 註冊首頁

Unity Shader實現2D遊戲迷霧

←手機掃碼閱讀     e36605 @ 2020-05-03 , reply:0

本文例項為大家分享了Unity Shader實現2D遊戲迷霧的具體程式碼,供大家參考,具體內容如下
先看效果吧。
我使用的是螢幕後處理效果,首先先去Photoshop做一張圖片如下,用畫筆點一個點就可以了,使用它來對攝像機擷取的圖片進行處理。
在攝像機上新增指令碼檔案
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestScript : MonoBehaviour { [Range(0,3)] public float Lerp = 0;//使用它來調整可視區域的大小 public Texture2D MaskTex; public Shader ScreanShader; public Material GetMaterial { get { if(_material ==null) _material = new Material(ScreanShader); return _material; } } private Material _material = null; //src是攝像機擷取到的照片,dest是處理過的圖片 void OnRenderImage(RenderTexture src, RenderTexture dest) { GetMaterial.SetTexture("_MainTex", src); GetMaterial.SetTexture("_MaskTex", MaskTex); GetMaterial.SetFloat("_Lerp", Lerp); Graphics.Blit(src, dest, GetMaterial); } }
對應的shader,思路就是把MaskTex的顏色翻轉一下然後直接乘上去就可以了,小數越乘越小,越小顏色越黑。

Shader "Wzhhh/MyShader2" { Properties{ _MainTex("MainTex",2D) = "white"{} _MaskTex("MaskTex",2D) = "white"{} _Lerp("Lerp",Range(0,3)) = 1 } SubShader{ Pass{ Tags{ "LightMode" = "ForwardBase" } CGPROGRAM #include "Lighting.cginc" #pragma vertex vert #pragma fragment frag sampler2D _MaskTex; sampler2D _MainTex; float4 _MainTex_ST; float _AlphaBase; float _Lerp; struct a2v { float4 vertex : POSITION; float2 texcoord : TEXCOORD0; }; struct v2f { float4 pos : SV_POSITION; fixed2 uv : TEXCOORD0; }; v2f vert(a2v i) { v2f o; o.pos = UnityObjectToClipPos(i.vertex); o.uv = TRANSFORM_TEX(i.texcoord, _MainTex); return o; } fixed4 frag(v2f o) :SV_TARGET{ fixed4 color = tex2D(_MaskTex, o.uv); color.r = 1 - color.r; color.g = 1 - color.g; color.b = 1 - color.b; fixed4 color2 = tex2D(_MainTex, o.uv); color2.r *= color.r*_Lerp; color2.g *= color.g*_Lerp; color2.b *= color.b*_Lerp; return color2; } ENDCG } } }


[e36605 ] Unity Shader實現2D遊戲迷霧已經有259次圍觀

http://coctec.com/docs/program/show-post-232650.html