Simple Fog in XNA

In this article I will be showing you how you can create a simple Fog in XNA.

Just reminding the sample will not be a real-fog but similar.

Ok lets start then

Create a new project in XNA 3.0 or XNA 3.1


Then add these variables:

GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;    
float aspectRatio;
Vector3 modelPosition2 = new Vector3(200.0f, 0.0f, 100.0f);

Vector3 cameraPosition2 = new Vector3(0.0f, 0.0f, 100.0f);  

We are adding cameraposition and modelposition.

After that add Models folder in Content region and import model with its textures.


Update your LoadContent,Update and Draw functions seen below:

protected override void LoadContent()
 spriteBatch = new SpriteBatch(GraphicsDevice);
 aspectRatio = graphics.GraphicsDevice.Viewport.Width / graphics.GraphicsDevice.Viewport.Height;

protected override void Update(GameTime gameTime)
  KeyboardState newstate = Keyboard.GetState();
  if (newstate.IsKeyDown(Keys.W))
    modelPosition2 += new Vector3(0.0f, 0.0f, 1.0f);
  else if (newstate.IsKeyDown(Keys.S))
    modelPosition2 -= new Vector3(0.0f, 0.0f, 1.0f);
  else if (newstate.IsKeyDown(Keys.A))
     modelPosition2 -= new Vector3(1.0f, 0.0f, 0.0f);
  else if (newstate.IsKeyDown(Keys.D))
     modelPosition2 += new Vector3(1.0f, 0.0f, 0.0f);
  else if (newstate.IsKeyDown(Keys.Escape))

protected override void Draw(GameTime gameTime)
  load_model(Content.Load<Model>("Models\\car"), modelPosition2 += new Vector3(0.0f, 0.0f, 0.0f), aspectRatio);

public void load_model(Model model_path, Vector3 camera_position, float aspect)
   Matrix[] transforms = new Matrix[model_path.Bones.Count];
   foreach (ModelMesh mesh in model_path.Meshes)
    foreach (BasicEffect effect in mesh.Effects)
      effect.FogEnabled = true;
      effect.FogStart = 35.0f;
      effect.FogEnd = 250.0f;
      effect.FogColor = new Vector3(255.0f, 255.0f, 255.0f);

      effect.View = Matrix.CreateLookAt(camera_position, Vector3.Zero, Vector3.Up);
      effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspect, 1.0f, 1000.0f);

Load model is a nice model loading function that you can use in your projects.

You can move the car with W,A,S,D keys on your keyboard.Try to get near the car.You will see the fog end/disappear.and then make the opposite.make it drive to the fog.



I know its not like you have hoped. This is called Fog Effect inside BasicEffect class.

I hope this article have helped you.

Araf Global is a software consultancy company founded in 2016 focusing on cutting edge technologies.