2

How to find an point where line1 and lin2 intersect, if both lines are defined by x,y,alpha where x,y are coordinates of a point on a line and alpha is the angle between the line and x=const?

I tried applying sine theorem but it yields two answers (triangles can be built on both sides of a line). I can check which point forms correct slope with one of the points, but that is ugly.

I can switch to y=ax+b representation, but then I have special cases that I have to worry about. Vertical and horizontal lines should be differently to avoid division by zero in 1/sin(alpha) and 1/cos(alpha) cases.

I am not looking for an implementation in a certain language, just a formula.

These questions are not relevant because they deal with finite line segments, NOT lines.

Given two points and two vectors, find point of intersection
How do you detect where two line segments intersect?

Community
  • 1
  • 1
Stepan
  • 1,391
  • 18
  • 40

2 Answers2

3

Suppose line 1 is defined by [x1, y1] and alpha1 and line 2 by [x2, y2] and alpha2.

Suppose k1 = tan(alpha1) and k2 = tan(alpha2).

Then the formula for the x-coordinate of the intersection is

x = (y2 - y1 + k1 * x1 - k2 * x2) / (k1 - k2)

Note: Function tan is undefined for angles pi / 2 + k * pi (where k is an arbitrary integer), so:

if k1 is undefined, then x = x1 and y = y2 + k2 * (x1 - x2)

if k2 is undefined, then x = x2 and y = y1 + k1 * (x2 - x1)

(both are practically the same with exchange of indices 1 <--> 2).

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • 1
    Is there a way to avoid check for `if(aplha1!=pi/2)`? Angles are guaranteed to be different, but one of them might be pi/2 causing div_zero error for tan(pi/2). – Stepan Oct 30 '16 at 15:32
  • Thank you for your warning about this special case, I extended my answer to include it. – MarianD Oct 30 '16 at 16:04
2

For a line equation Y = aX + b, you can calculate a = tan(alpha).

So if line1 is defined as x, y and alpha, the equation is Y = tan(alpha) * X + b.

Now to find b, you need a point on your line. This point has coordinates (x, y).

y = ax + b

b = y - ax

So you line equation is:

Y = tan(alpha) * X + (y - tan(alpha) * x)

Now you only have to solve the lines equation:

Y = a1 * X + b1

Y = a2 * X + b2

Which is:

a1 * X + b1 = a2 * X + b2

(a1 - a2) * X = b2 - b1

X = (b2 - b1) / (a1 - a2)

Right now you can calculate Y too.

So if we replace, we obtain:

X = ((y2 - tan(alpha2) * x2) - (y1 - tan(alpha1) * x1)) / (tan(alpha1) - tan(alpha2)

Simplified:

X = (y2 - y1 - tan(alpha2) * x2 + tan(alpha1) * x1)) / (tan(alpha1) - tan(alpha2)

And then:

Y = tan(alpha1) * X + (y - tan(alpha1) * x

Ludonope
  • 963
  • 9
  • 14