Activity › Forums › Adobe After Effects Expressions › Check for shortest distance
-
Check for shortest distance
Posted by Klaus Hertweck on May 21, 2025 at 6:45 amI have shapes A and B. A is stationary and B is moving across the screen. I want to calculate the frame when B is closest to A. I guess it’s done with a For Loop and distance but I cannot figure out the expression.
Brie Claytonreplied 11 months, 4 weeks ago 3 Members · 4 Replies
-
4 Replies
-
Klaus Hertweck
May 21, 2025 at 12:36 pmI figured out the correct expression myself.
First, I set up a null with an expression controls Slider Control “check distance” (just to do some of the calculations).
There, I calculated the distance:
var posA = thisComp.layer(“Shape A”).transform.position;
var posB = thisComp.layer(“Shape B”).transform.position;
var distance = length(posA, posB);
distanceOn another slider, I set up the frame expression:
var distance = effect(“check distance”)(“Slider”);
var compLength = thisComp.duration / thisComp.frameDuration;
for (i = 0; i <= compLength; i++) {
if (distance.valueAtTime(framesToTime(i+1)) >= distance.valueAtTime(framesToTime(i))) break
}
iI would have liked to put all the expressions onto a single slider. However, when I insert length(posA, posB).valueAtTime(framesToTime(i) into the expression, I get an error: This is not a function.
Is there a way to get around this error?
-
Dan Ebberts
May 21, 2025 at 12:50 pmThis could get complicated, depending on what you’re after, but the simplest version would probably be something like this:
posterizeTime(0);
p1 = thisComp.layer("Shape Layer 1").content("Rectangle 1").transform.position;
p2 = thisComp.layer("Shape Layer 1").content("Rectangle 2").transform.position;
minD = length(p1.valueAtTime(0),p2.valueAtTime(0));
for (i = 1; i < timeToFrames(thisComp.duration); i++){
t = framesToTime(i);
d = length(p1.valueAtTime(t),p2.valueAtTime(t));
minD = Math.min(d, minD);
}
minD
Reply to this Discussion! Login or Sign Up