Search code examples
c#algorithmlinear-algebra

Algorithm for intersection of 2 lines?


I have 2 lines. Both lines containing their 2 points of X and Y. This means they both have length.

I see 2 formulas, one using determinants and one using normal algebra. Which would be the most efficient to calculate and what does the formula looks like?

I'm having a hard time using matrices in code.

This is what I have so far, can it be more efficient?

public static Vector3 Intersect(Vector3 line1V1, Vector3 line1V2, Vector3 line2V1, Vector3 line2V2)
{
    //Line1
    float A1 = line1V2.Y - line1V1.Y;
    float B1 = line1V1.X - line1V2.X;
    float C1 = A1*line1V1.X + B1*line1V1.Y;

    //Line2
    float A2 = line2V2.Y - line2V1.Y;
    float B2 = line2V1.X - line2V2.X;
    float C2 = A2 * line2V1.X + B2 * line2V1.Y;

    float det = A1*B2 - A2*B1;
    if (det == 0)
    {
        return null;//parallel lines
    }
    else
    {
        float x = (B2*C1 - B1*C2)/det;
        float y = (A1 * C2 - A2 * C1) / det;
        return new Vector3(x,y,0);
    }
}

Solution

  • Assuming you have two lines of the form Ax + By = C, you can find it pretty easily:

    float delta = A1 * B2 - A2 * B1;
    
    if (delta == 0) 
        throw new ArgumentException("Lines are parallel");
    
    float x = (B2 * C1 - B1 * C2) / delta;
    float y = (A1 * C2 - A2 * C1) / delta;
    

    Pulled from here