2D Fog Of War

This content may move. Please update your bookmark to point to http://vdir.us/go/2d-fog-of-war

Fog Of War Sample

This tutorial covers a basic way of implementing two dimensional fog of war for a game in XNA and assumes you (the reader) has basic knowledge of C# and the XNA Framework. To get things started, create an empty Windows game project. Two textures will be needed: one for the Light and one for the Background. After adding these to the Content Project, go ahead and add the following members to the game class.

Texture2D lightTexture;
Texture2D backgroundTexture;

RenderTarget2D lightTarget;
RenderTarget2D mainTarget;

Effect basicFogOfWarEffect;

While the use of the texture fields is obvious, the use of the render targets may not. The concept behind this fog of war implementation is to draw the light texture to the lightTarget render target and then use the produced texture as the alpha channel for the texture produced from the mainTarget render target.

Continue reading

Zune HD: Calling GetState Twice

Beware that when you call TouchPanel.GetState twice within the game loop, what touch locations had a Pressed state the first time will have a Moved state the second time. Consider the following lines of code.

TouchCollection touches = TouchPanel.GetState();

foreach (TouchLocation locale in touches)
{
    if (locale.State == TouchLocationState.Released && locale.Id == id1)
        id1 = -1;
    else if (locale.State == TouchLocationState.Pressed && id1 == -1)
        id1 = locale.Id;
    else if (locale.Id == id1)
        pos1 = locale.Position;
}

touches = TouchPanel.GetState();

foreach (TouchLocation locale in touches)
{
    // Can fail if the first time through it was Pressed.
    if (locale.Id == id1 && locale.State == TouchLocationState.Pressed)
    {
        // Do something important
    }
}

Note that it isn’t important that these are in the same file let alone the same method. You cannot rely on having access to the same state data everytime you call GetState within the game’s loop. So it will probably become important to put the touch code in a global location and store the states for the duration of the loop. For instance you can store the TouchCollection data in a static variable at the top of the Game’s Update method.

How To: Zune HD Touch Testing

Touch Testing on Zune HD

One of the first “games” I made for the Zune HD was a simple little application to test how accurate and quick the touch panel is. This How To gives you the code to get started with your own basic testing application.

After creating a Zune game with XNA 3.1, the first thing you need to do is define a basic particle struct to hold some data that we track as the user touches the screen. Specifically we need to track whether or not a particle is active (do we update it and draw it?), its position and its life (how long it has been there). I created this structure within the Game1 class but really it can go anywhere.

Continue reading