Monday, October 1, 2012

Fog of War

This is an old post migrated from my previous blog (10/01/2012). I apologize if any info seems outdated.

Many RTS games have a fog of war system. I want to share a portion of code that I used to accomplish this in Unity for the MOBA Project. I used a fairly basic approach and there are certainly more elegant ways to accomplish this. I will be showing how to calculated the pixel of intersection of a plane that is the fog of war.
First, I created the fog by placing a plane over the entire level. The plane has a dark translucent material in order to look something like fog. Then the idea is that; when a player or unit is between the fog and the camera, an area in the texture would be alphaed    out exposing that portion of the map.
To figure out the point in the texture between the unit/player and the camera I used a raytrace. Be sure to set up a mask, that way you only are casting against the plane that is the fog of war.
LayerMask mask = LayerMask.NameToLayer("FogOfWar");
RaycastHit hit;
mask=~mask;
if(Physics.Raycast(ray, out hit, dist, mask.value))
{//calc intersect pixel here}
Pixel data is stored as a 1D array. Only the texture coordinate information from the Raycast is available. What is important to is the actual pixel where the ray intersects with the fog of war plane. The code below is how to calculate that pixel from texture coordinate information.
if(hit.collider == null)
return;
Texture2D tex = hit.collider.renderer.material.mainTexture as Texture2D;
if(tex == null)
return;
int row = (int)(tex.width * hit.textureCoord.x); //row
int column = (int)(tex.height * hit.textureCoord.y);//col
 
//calc pixel in via text coords
int pixIn = (column * tex.width) - (tex.width - row);
//now alpha this pixel and an area around it
}
In the code above, pixIn and an area around it will be alphaed exposing the map below the fog.
From there it us up to you how to alpha the texture. I’m currently doing this procedurally with a buffer. I hope this helps someone getting started on a system like this. I’ll post some pics below of my first iteration. Please post any questions in the comments.