Unity Shader实现2D游戏迷雾

2020-04-29,

本文实例为大家分享了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
 }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

《Unity Shader实现2D游戏迷雾.doc》

下载本文的Word格式文档,以方便收藏与打印。