BasicEffect Fog


In the past couple of tutorials, we have been talking about how to use the BasicEffect class to make our models look nice. One of the built-in features they have is fog. It is not incredibly fancy, but it has a pretty nice effect. In this tutorial, we will look at how to do fog with the BasicEffect class. It might be a good idea to start with the code from the lighting tutorial, but you could also start with the code from the tutorial about using 3D models.

Rendering Fog with the BasicEffect Class

Doing fog is actually very simple. If you are using the code from one of the previous tutorials, then all we need to do is add the following lines of code inside the inner loop in the DrawModel() method:

effect.FogEnabled = true;
effect.FogColor = Color.CornflowerBlue.ToVector3(); // For best results, make this color whatever your background is.
effect.FogStart = 9.75f;
effect.FogEnd = 10.25f;

The first line tells the BasicEffect that we want to have fog. The second line says what color to use for the fog. As a general rule, it is a good idea to have the fog color be the same as the background color, which in this case is cornflower blue. The last two lines state where the fog begins and where it ends. FogStart is how far away from the camera you have to be before fog starts appearing. Anything closer than this distance will not be obscured by fog at all. FogEnd says how far away an object needs to be in order for it to be completely covered in fog. In our case, we picked 9.75 and 10.25, because in the code, the model is 10 units away, and about 1 unit in thickness. I've picked these numbers so that it is easy to see the fog. When you run the program you should see something similar to the image below.

You can, and should, change the fog color, start, and end values to get the visual appearance that you want.


Get the full source code for this project:

What's Next?

This completes the set of tutorials on the BasicEffect class. You might also be interested in some of the tutorials on animating 3D objects if you haven't already, or if you are interested in learning more about effects, you might want to look at the tutorials on HLSL and creating your own effects.

Troubleshooting.png Having problems with this tutorial? Try the troubleshooting page!