# After Effects: Detect if Lines are Intersecting

I have two lines (The lines are imaginary, i have two Nulls as endpoints for each line) I want a fifth Null two appear where the lines intersect. I have used this code so far:

``````p1 = thisComp.layer("red_end").transform.position;
p2 = thisComp.layer("red_start").transform.position;
p3 = thisComp.layer("blue_end").transform.position;
p4 = thisComp.layer("blue_start").transform.position;

m1vert = Math.abs(p1-p2) < .0001;
m2vert = Math.abs(p3-p4) < .0001;

if (! m1vert){
m1 = (p2-p1)/(p2-p1);
b1 = p1-m1*p1;
}
if (! m2vert){
m2 = (p4-p3)/(p4-p3);
b2 = p3-m2*p3;
}
if (m1vert && m2vert){
x = value;
y = value;
}else if(m1vert){
x = p1;
y = m2*x + b2;
}else if (m2vert){
x = p3;
y = m1*x + b1;
}else if (m1 == m2){
x = value;
y = value;
}else{
x = (b1-b2)/(m2-m1);
y = m1*x +b1;
}
[x,y]
``````

The fifth Null does appear in the intersections when the lines intersect, but also miserably stumble around on screen when the lines don't intersect. I want the Null to go to a specific position whenever the lines don't intersect. So how would I do that? Any help is appreciated.

The fifth null doesn't wander randomly, it just extends the red and blue lines off beyond their ends. You need to detect whether the intersection point is on the segment between the start and end nulls for each line.

You can test for it with this rather horrifying conditional: basically it tests to see if the intersection is outside the bounds of each point's x then y coordinates.

Replace the last line of your expression with this:

``````if ((x > p1 && x > p2)||(x > p3 && x > p4)||(x < p1 && x < p2)||(x < p3 && x < p4)||(y > p1 && y > p2)||(y > p3 && y > p4)||(y < p1 && y < p2)||(y < p3 && y < p4)){
value
}else{
[x,y]
}
``````

Another version, does the same thing but with nice readable code, and a re-useable function:

``````function outsideBounds(samplePt, p1, p2){
if (samplePt > Math.max(p1, p2)) {return true}
if (samplePt > Math.max(p1, p2)) {return true}
if (samplePt < Math.min(p1, p2)) {return true}
if (samplePt < Math.min(p1, p2)) {return true}
return false
}

if (outsideBounds([x,y], p1, p2)||outsideBounds([x,y], p3, p4)){
value
}else{
[x,y]
}
``````