You copied the Doc URL to your clipboard.

Procedural linear fog

Ensure that the further away the object is, the more its colors fade to the defined fog color. To achieve this in your fragment shader, you can use simple linear interpolation between the fragment color and the fog color.

The following example code shows how to calculate the fog color in the vertex shader, based on the distance to the camera. This color is passed to fragment shader as a varying.

output.fogColor = _FogColor * clamp(vertexDistance * _FogDistanceScale, 0.0, 1.0);

Where:

  • vertexDistance is the vertex to camera distance.

  • _FogDistanceScale is a factor passed to the shader as a uniform.

  • _FogColor is the base fog color you define and passed as a uniform.

In the fragment shader the interpolated input.fogColor is combined with the fragment color output.Color.

outputColor = lerp(outputColor, input.fogColor.rgb, input.fogColor.a);

The following figure shows the result you get in your scene:

Figure 5-55 Linear fog based on distance


Note

Calculating the fog in a shader means you are not required to do any extra post processing to produce the fog effect.

Try to merge as many effects as possible into one shader. However, ensure you check performance because if you exceed the cache, performance might reduce. You might have to split the shader into two or more passes.

You can do the fog color calculation in the vertex or fragment shader. The calculation in the fragment shader is more accurate but requires more compute performance because it is calculated for every fragment.

The vertex shader calculation is lower precision but is also higher performance because it is only computed once per vertex.

Was this page helpful? Yes No