Unity shader realizes 2D game fog

Time:2020-10-26

In this paper, we share the specific code of unity shader to realize 2D game fog for your reference. The specific content is as follows

Let’s see the effect first.

I use the post-processing effect of the screen, first go to Photoshop to make a picture as follows, click a point with a brush, and use it to process the image captured by the camera.

Add script file to camera

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class TestScript : MonoBehaviour
{
 [Range(0,3)]
 Public float LERP = 0; // use it to adjust the size of the visible area
 public Texture2D MaskTex;
 public Shader ScreanShader;
 public Material GetMaterial
 {
  get
  {
   if(_material ==null) _material = new Material(ScreanShader);
   return _material;
  }
 }
 private Material _material = null;
 //SRC is the photo captured by the camera and dest is the processed image
 void OnRenderImage(RenderTexture src, RenderTexture dest)
 {
  GetMaterial.SetTexture("_MainTex", src);
  GetMaterial.SetTexture("_MaskTex", MaskTex);
  GetMaterial.SetFloat("_Lerp", Lerp);
  Graphics.Blit(src, dest, GetMaterial);
 }
}

The idea of the corresponding shader is to flip the color of masktex and multiply it directly. The smaller the decimal, the darker the color.


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
 }
 }
}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

Api: tiktok: user video list

Tiktok tiktok, tiktok, tiktok, Api, Api, jitter, voice, bullet screen comments, jitter, jitter, and jitter. Tiktok tiktok tiktok data, jitter data acquisition, live broadcast of shaking sound Titodata: professional short video data acquisition and processing platform. For more information, please contact:TiToData Massive data collection Collect 500 million pieces of data for customers every day Tiktok […]