Search code examples
javaline

Line class intersectionWith method implemantion


hello I need to implemnt the follwing method of Line class, in java:

// Returns the intersection point if the lines intersect,
// and null otherwise.
public Point intersectionWith(Line other) { }

I am afraid I am not farmiler with the math calcuations involoved. can someone may help or reffer me to a place I can understand? regards!


Solution

  • I will assume that you are using Lines and Point that you created yourself and that are in 2D. If your Lines are defined by the equation y = a*x + b, and you store the coefficient a and b, then the intersection between two lines would be (x,y) such that y == a1*x + b1 == a2*x + b2

    You can find x as: x = (b2 - b1) / (a1 - a2) Note that there is no solution if a1 == a2, that is, if the two lines are parallel. Then, you can compute y = a1*x + b1