Distance Fields

In this tutorial we will learn about Distance Fields.




[IMPORTANT]
If you are visiting this website for the very first time, please have a look at the first tutorial, it would help you to understand this tutorial better.
Click Here !

Project Setup

First add a plane then rotate it's face toward camera, or set the plane rotation to (90, 180, 0).
Add a unlit shader and apply it to a material, and apply that material to the plane.

open the Unlit Shader in Visual Studio.

Bootstrap Themes



With this rotation of plane, the origin of i.uv is bottom left corner.

Bootstrap Themes

Define 3 local points.
(Mentioned with green cells)

Bootstrap Themes
Bootstrap Themes

Fragment Function during its one call go through all pixels to define its color.
Each pixel have a different value of i.uv.x & i.uv.y.

At each pixel we will calculate the distance between i.uv and these 3 points, and we will keep the minimum distance and neglect the other 2 large distances.
And we will multiply that minimum distance value with the color.

In current example we calculated the distance between i.uv [0.3, 0.13] at pixel A with these 3 points, and keep the minimum distance 0.21, to multiply it with color at that pixel.

Bootstrap Themes

Min(float A, float B)
If you input 2 numbers, it will return tha smaller number. e.g min(2, 4) = 2

When loop index is x = 0, we calculted the distance(d) between i.uv [0.45, 0.34] at pixel V and Point[0], and compare it with (Distance = 1.0) using min() function, and keep the minimum distance. (0.19)
When loop index is x = 1, distances(d) between i.uv [0.45, 0.34] and Point[1] is 0.45, we compare it with previous value (Distance = 0.19) and we keep the minimum distance. (0.19)
When loop index is x = 2, distances(d) between i.uv [0.45, 0.34] and Point[2] is 0.6, we compare it with previous value (Distance = 0.19) and again we keep the minimum distance. (0.19)

When we came out of loop we multiply that minimum distance with the color.

That is just for one pixel, and all the pixels will do these calculations, and will multiply the minimum distance with the color.


At pixel A the minimum distance is very small so color is black.
At pixel B the minimum distance is large so color is grey.
At pixel C the minimum distance is even larger, results in light grey color.

Bootstrap Themes
Bootstrap Themes
Bootstrap Themes

Increaese the numbers of points from 3 to 30, and initialize the positions using the RandomFloat2() function. (mentioned with orange cell)
Multiplying 4 with distance to make it a little brighter.

Bootstrap Themes
Bootstrap Themes

To move the points in random directions just add the line mentioned with orange cell.
Points will move in Unity Editor's Play Mode.

Bootstrap Themes