XNA 2D Fog of War / Basic Lighting

A friend of mine asked me how to make lights for a 2D game in XNA he’s working on, so I threw together a small example:


protected override void Draw(GameTime gameTime)
{
//Börja med att rita en textur med svart bakgrund och vitt där man vill ha "ljus"
GraphicsDevice.SetRenderTarget(fogTarget);
GraphicsDevice.Clear(Color.White * 0.1f);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
spriteBatch.Draw(gradient, new Rectangle(100, 100, 400, 400), Color.Blue);
spriteBatch.Draw(gradient, new Rectangle(400, 30, 400, 400), Color.White);
spriteBatch.Draw(gradient, new Rectangle(100, 30, 400, 400), Color.Red);
spriteBatch.End();

//Resetta rendertarget
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.CornflowerBlue);

//Rita ut allting som vanligt
spriteBatch.Begin();
spriteBatch.Draw(cat, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), null, Color.White);
spriteBatch.End();

//Sätt blendstate till nåt häftigt o rita ut foggen (alpha och color måste vara samma för source/destination)
BlendState blendState = new BlendState();
blendState.AlphaDestinationBlend = Blend.SourceColor;
blendState.ColorDestinationBlend = Blend.SourceColor;
blendState.AlphaSourceBlend = Blend.Zero;
blendState.ColorSourceBlend = Blend.Zero;

spriteBatch.Begin(SpriteSortMode.Deferred, blendState, null, null, null);
spriteBatch.Draw(fogTarget, Vector2.Zero, Color.White);
spriteBatch.End();

base.Draw(gameTime);
}

 
Warning: count(): Parameter must be an array or an object that implements Countable in /customers/8/5/a/martinpersson.org/httpd.www/wordpress/wp-includes/class-wp-comment-query.php on line 405

2 Responses to “XNA 2D Fog of War / Basic Lighting”

  1. […] found a good 2D Fog of War example, which helped me understand how to create the lighting effect.  First of all, I had to […]

  2. […] found a good 2D Fog of War example, which helped me understand how to create the lighting effect.  First of all, I had to […]

Leave a Reply