Distance

When working with with shaders or other mathbased systems, it's often useful to use the distance between two points, or the distance from one point to a whole bunch of pixels. It can be used for masking or offsetting things.

Many engines have a distance node, but following is the procedure to find the distance and how to massage it so it's useful.

First, you need to find a vector between two points. In the case of a shader, you'll want to find a vector between the point and all the fragments on the object.

In this image, the pink dot is the position you want to measure from, and the squares are the fragments.

To find a vector between two points you subtract one from the other (the order of the subtraction determines the direction of the vector. In this case it doesn't matter).

PositionA - PositionB = VectorAB.

Now, if we do this in a shader, it'll look like this:

PositionA - WorldPosition.

The vectors will update even if you move PositionA around.

https://gfycat.com/memorablecreepyiberianmidwifetoad

Now that we have the vectors, we can check how long they are by getting their length.

length(PositonA - WorldPosition)

This will give us a single value saying how far PositionA is from PositionB. In this example, we can see the values range from 0 - 10.

This will of course also update as the the positions move around.

It's often useful to remap or "fit" this range of values into a 0-1 range. The way to do it varies per application, but you want to grab a minimum distance and a maximum distance and map it to 0 and 1.

This leaves us with: fit(length(PositionA -WorldPosition),MinimumDistance,MaximumDistance,0,1))

Now we have a range that goes from 0-1 by the corner. It's often useful to invert the range so the 1 is at the center and the 0 is at the maximum range. Like this:

fit(length(PositionA -WorldPosition),MinimumDistance,MaximumDistance,1,0))

To make this a bit more useful you can imagine the numbers as color intensity in a black and white mask. So it would be fully white in the center and black at the edge.

It's easier to see if we decrease the maximum distance a bit and increase the resolution of the example.

This will generate a smooth mask surrounding your PositionA at all times.

https://gfycat.com/hotgloomykitten

And that's it! This mask can be used for tons of different effects.