Wednesday, January 4, 2012

XNA : Ambient 2D Light

Hi,

To apply an ambient light in your game,a very simple way without using shaders.
To do this, simply edit color when Draw each sprite.


Add a the top of your game class :

float ambient = 1f;
Color ambientColor = Color.White;

 In the Update method :

 KeyboardState c = Keyboard.GetState();
 if (c.IsKeyDown(Keys.Space))
 {
    ambient -= 0.01f;
    if (ambient <= 0)
       ambient = 1f;
 }

And finally , to apply ambient on sprites :

Color drawColor = new Color(ambientColor.R / 255f * ambient, ambientColor.G / 255f * ambient, ambientColor.B / 255f * ambient);
spriteBatch.Begin();
spriteBatch.Draw(mySprite, new Vector2(0,0), drawColor);
spriteBatch.End();

As you see, it's very easy :) With this, you could simulate for example day cycle.

No comments:

Post a Comment