Skip to content

Instantly share code, notes, and snippets.

@Cyanilux
Created November 17, 2021 16:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cyanilux/19c041797dbb53bb72648e91d4e4f866 to your computer and use it in GitHub Desktop.
Save Cyanilux/19c041797dbb53bb72648e91d4e4f866 to your computer and use it in GitHub Desktop.
Fog of war example using Graphics.Blit. But probably not very optimised.
using UnityEngine;
public class FogOfWarHandler : MonoBehaviour {
public RenderTexture rt_units; // Render Texture asset, stores circles around units
public RenderTexture rt; // Render Texture asset, combines rt_units with rt from previous frame
public Material material_cloudBrush; // shader : max(_MainTex, brush), where brush is a circle drawn at _Pos with _Radius and _Edge (softness)
public Material material_combine; // shader : max(_MainTex, _OtherTex)
public FogOfWarUnit[] units; // MonoBehaviour with public float properties : radius and softness
public float mapSize = 20;
private RenderTextureDescriptor descriptor;
private void Start() {
Graphics.SetRenderTarget(rt);
GL.Clear(true, true, Color.black);
descriptor = rt.descriptor;
Shader.SetGlobalFloat("_FogMapSize", mapSize); // Used in cloud/fog shader, uvs for texture projection : (0.5, 0.5) - positionWS.xz / _FogMapSize
}
public void FixedUpdate() {
// Clear rt_units
Graphics.SetRenderTarget(rt_units);
GL.Clear(true, true, Color.black);
// Get Temporary
RenderTexture temp = RenderTexture.GetTemporary(descriptor);
temp.name = "temp";
// Ping pong render textures as we can't (or shouldn't) use blit with same source/destination
RenderTexture prev = rt_units;
RenderTexture next = temp;
for (int i = 0; i < units.Length; i++) {
FogOfWarUnit unit = units[i];
Vector2 pos = new Vector2(unit.transform.position.x, unit.transform.position.z);
pos /= -mapSize;
pos += Vector2.one * 0.5f;
material_cloudBrush.SetVector("_Pos", pos);
material_cloudBrush.SetFloat("_Radius", unit.radius / mapSize);
material_cloudBrush.SetFloat("_Edge", unit.softness / mapSize);
//Debug.Log(i + " : blitting " + prev.name + " to " + next.name);
Graphics.Blit(prev, next, material_cloudBrush);
(prev, next) = (next, prev);
}
if (prev == temp) {
// If ended on temp rt, copy to rt_units
Graphics.Blit(temp, rt_units);
}
// copy rt_units to rt
material_combine.SetTexture("_OtherTex", rt_units);
Graphics.Blit(rt, temp, material_combine);
Graphics.Blit(temp, rt);
// Release Temp
RenderTexture.ReleaseTemporary(temp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment