Simple 2D Shadows in XNA






private Texture2D treeTop; 

treeTop = content.Load<Texture2D>(@"Tiles/canopy145"); 

You'll need your spriteBatch.Draw statements sandwiched in between spritebatch.begin and spritebatch.end in your main draw method as usual.

spriteBatch.Begin(SpriteBlendMode.AlphaBlend,SpriteSortMode.BackToFront, SaveStateMode.None, camera.Transform);




I use a 2dCamera in my little game thus the camera.Transform but you don't need this for this example.

Now if you want to extend this, you could make color a variable and make your shadow x, y positions variables.  Then you could adjust your shadow position and transparency based upon wherever you want your sun.  If you want to go crazy, you could have a day night cycle and alter your shadow positions and transparency based upon the time of day.  That would be cool in an RPG.

In order to make color a variable, one way I have found that you can do it is to make color a Vector4.

Notice how I use the variable color in place of Color.White or New Color() in the second draw statement.  The only thing to keep in mind is when you make color a Vector4, you're now using floats instead of bytes.  So color is from 0 - 1.

You can apply the exact same logic to a player character.  The added benefit is your X, Y offsets for your shadows all stay the same for every direction you draw your character, thus your shadows appear consistant as you turn your character.  Here is a video of my character running and circling.  I increased the alpha to 80 so the video would show the shadow better.  I offset the player rectangle X +10 and Y - 5 on every player animation.  So all player animations have the same offset.  This places my Sun somewhere in the Southwestern sky.  It's easier to see the shadows if you watch the video in HD.