Question

I have two lines UV and PQ, with U(15,10) V(50,25) and P(40,10) and Q(30,30).

and i am finding a point of intersection between these two points. I am forming two linear equations for that:

eq 1:

Ux + t(Vx-Ux) = Px +s(Qx-Px)

eq2

I want to solve these equations using C program to get the value of either t or s.

I used the t from second equation and substituted it in first equation to get a formula to find s. But it did not work out. How can I solve this in a program?

No correct solution

OTHER TIPS

Use this equation Intersection of 2 Lines. You can use either the long expanded form, or abstract out a function that calculates a 2x2 determinant. Be careful of using integers, you might overflow.

int s,sa,sb;

Okay, sa is an integer.

sa=1/((Vx-Ux)*(Qy-Py)-(Qx-Px)*(Vy-Uy));

Since these are all integers, you're taking the reciprocal of an integer using integer math. The result is infinity if the integer is zero, one if it's one, negative one if it's negative one, and zero if it's anything else. So sa only has three possible values, or you crash.

Perhaps you should consider not using integer math? Maybe float sa; and sa = 1.0 / (....

Find the gradient of UV and PQ

The gradient of UV is : m = (Vy-Uy)/(Vx-Ux). And then find c by using y = mx + c since we know the value of y, m, x. Do that step again for PQ.

After you have 2 equations, you can find the intersection point by using substitutions. And finally, apply that to your c code.

OP's comment says "find intersection for two line segment".

AS OP provided pseudo-code, I assume C-like pseudo-code is wanted.

  1. Change each line into a parametrized form P(t) = b + m*t (use double)
    UV_m.x = V.x - U.x
    UV_m.y = V.y - U.y
    UV_b.x = U.x
    UV_b.y = U.y
    // same for PQ
    // Now your have 2 2-dimensional equations.
    // Puv(t1) = UV_b + UV_m * t1 and
    // Ppq(t2) = PQ_b + PQ_m * t2

  2. Assume Puv(t1) == Ppq(t2) for some t1,t2 (that is they are not parallel).
    UV_b.x + UV_m.y * t1 = PQ_b.x + PQ_m.x * t2
    UV_b.y + UV_m.y * t1 = PQ_b.y + PQ_m.y * t2

  3. Solve the 2D Matrix equation (I assume OP can solve 2D matrix, advise otherwise) If the determinate is 0.0, the lines are parallel, handle that as a special case. (They could be co-indecent and may/may not overlap.)

    [UV_m.x - PQ_m.x][t1] = [PQ_b.x - UV_b.x]
    [UV_m.y - PQ_m.y][t2] = [PQ_b.y - UV_b.y]

  4. At this point, if t1 and t2 are both in the range 0.0 <= t <= 1.0, the segments intersect! Finding the point of intersection is found simple by Puv(t1) = UV_b + UV_m * t1.

This method handles vertical lines well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top