How does this code Find the intersection point between two lines

cross productgeometryinner-productssolid-geometryvectors

I've been racking my brain for a while trying to step through this. This is Unity C# code used to find the position of intersection between two lines.
The full function is here Because of my usecase I know the lines intersect, I assumed that I could skip the coplanar/parallel checks.(I had to because of float shenanigans).

I haven't taken a math class with vectors since 2014 so I don't know what terms or properties to google.

inLineVec is the direction of the line. inLinePoint is a point on that line.

        Vector3 lineVec3 = inLinePoint2 - inLinePoint1;
        Vector3 crossVec1and2 = Vector3.Cross(inLineVec1, inLineVec2);
        Vector3 crossVec3and2 = Vector3.Cross(lineVec3, inLineVec2);
        float planarFactor = Vector3.Dot(lineVec3, crossVec1and2);

        float dot = Vector3.Dot(crossVec3and2, crossVec1and2);
        float s = Vector3.Dot(crossVec3and2, crossVec1and2) / crossVec1and2.sqrMagnitude;
        inIntersection = inLinePoint1 + (inLineVec1 * s);
        return inIntersection;

Best Answer

You have the first line $q_1(t) = P_1 + t V_1 $ and the second line $ q_2(s) = P_2 + s V_2$

Assuming $q_2(s)$ lies on $q_1(t)$ for some $s, t$ then we must have

$ P_1 + t V_1 = P_2 + s V_2 $

from which,

$ t V_1 - s V_2 = P_2 - P_1 $

Now, if you cross $(P_2 - P_1)$ with $V_2$ you get

$V_4 = (P_2 - P_1) \times V_2 = (t V_1 - s V_2) \times V_2 = t (V_1 \times V_2)$

Therefore, we can solve for $t$, using the dot product of both sides of the above equation with the vector $(V_1 \times V_2)$, i.e.

$ t = \dfrac{ V_4 \cdot (V_1 \times V_2) } { (V_1 \times V_2) \cdot (V_1 \times V_2 ) } = \dfrac{ V_4 \cdot (V_1 \times V_2) } { \| V_1 \times V_2 \|^2 }$

Now that we have $t$ , we can compute the point of intersection as

$ Q = P_1 + t V_1 $

And this is what the code says.