Effortless Layer Interaction: Master Proximity Detection in After Effects

Let’s suppose we just need a simple proximity detector. We want to cause a layer to change colors when another layer comes within a certain distance. This doesn’t need to be as precise as a collision detector, where we would want to know if any visible pixels of two layers overlap.

What we need to do here is create a loop that will examine each of the other currently active layers with video content and see if any of them is close enough to trigger the proximity condition. In this case we’ll just have the layer change color when it is close to another layer. We’ll do this by crafting our expression for the Color parameter of a Fill effect.

In this case, if we use round shapes, our setup will approximate a collision detector because we will use the distance between two layers as the proximity condition. This turns out to be half the sum of the two layer widths.

Note #1; Original expression was created by Dan Ebberts. However, when I was researching it for this email the width calculation did not work properly. I’ve corrected the calculations to:
(layer1.sourceRectAtTime(time, false).width + 
layer2.sourceRectAtTime(time, false).width)/2;
Note #2: You might think: “OK, but they are right next to each other. What if they are far apart?”. Good question!
We need to calculate the minimum distance between them and the real distance. Once we compare them we will understand if they are close or not.
Note #3: For efficiency, we will want to break out of the loop as soon as we find one layer that meets the proximity condition.

Copy the code to the color property:

out = [1, 1, 0, 1];
 for (i = 1; i <= thisComp.numLayers; i++){ 
if (i == index) continue; L = thisComp.layer(i); 
if (! (L.active && L.hasVideo)) continue;
delta = (thisLayer.sourceRectAtTime(time, false).width + 
L.sourceRectAtTime(time, false).width)/2;
  if (length(position, L.position) <= delta){ 
    out = [1, 0.25, 0, 1]; 

Pro tip: Remember that in expressions, 
colors are represented as four-element arrays 
in the form [red, green, blue, alpha] 
where each value is a number between zero 
and one. So in our example, [1, 1, 0, 1] 
represents bright yellow.


Source https://motionscript.com/design-guide/proximity.html

Pro tip: Go to AEJuice Pack Manager – Expressions Pack to apply this expression in 1 click. Here are direct links for the latest plugin version:
Windows / macOS

Click here to receive more tips by email.