user11790565
user11790565

Reputation: 5

C++ : how to know if a point I intersects two line segments?

I have two line segments given by their equations A1x + B1y + C1 = 0 and A2x + B2y + C2 = 0, the coordinates of the intersection point I of these two line segments can be computed as follows:

x1 =B2*C1 − B1*C2 / A2*B1 − A1*B2

y1 =A1*C2 − A2*C1 / A2*B1 − A1*B2

I'm working with double values, how to know if I=(x1,y1) intersects the two line segments?

I tried replacing the values of x1 and y1 in the equations of the line segments but it doesn't seem to work

Upvotes: 0

Views: 113

Answers (2)

arsdever
arsdever

Reputation: 1262

Another approach could be the calculation of 2 constants for both lines (the angle tangent and offset) and checking intersection with them

(L1) y1 = k1 * x1 + b1
(L2) y2 = k2 * x2 + b2

// where

k1 = A1 / B1 and b1 = C1 / B1
k2 = A2 / B2 and b2 = C2 / B2 

// If they intersect (y1 == y2) and (x1 == x2)
// Subtract them and you will get
0 == (k1 - k2) * x + (b1 - b2)
x = (b2 - b1) / (k1 - k2)
// After getting the x
y = k1 * x + b1 or y = k2 * x + b2

To check, whether they intersect or not you can check if (k1 == k2) To check, whether they are perpendicular, you can check if (k1 * k2 == -1)

Upvotes: 0

Paul Evans
Paul Evans

Reputation: 27567

You'll need brackets:

x1 = (B2*C1 − B1*C2) / (A2*B1 − A1*B2);
y1 = (A1*C2 − A2*C1) / (A2*B1 − A1*B2);

Upvotes: 1

Related Questions