I need an algorithm that can find the intersection of two 2D lines. Each line will come in the form of a point on the line and the dx/dy of a parallel vector. I've tried parameterizing each line and solving the system of equations to solve for the parameterized variable which I could plug back into the parametric equation of the lines and get my x/y, but my attempt failed. Any ideas? I'm programming in Python but the language doesn't much matter.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You basically have to solve the following equation:
x = x0,a+dxa×t
y = y0,a+dya×t
x = x0,b+dxb×u
y = y0,b+dyb×u
Or:
x0,a+dxa×t = x0,b+dxb×u
x0,a+dxa×t = x0,b+dxb×u
Now if you do some algebraic manipulation, you will find that:
t=dyb×(x0,b-x0,a)-dxb×(y0,b-y0,a)/d
u=dya×(x0,b-x0,a)-dxa×(y0,b-y0,a)/d; where
d=dxa×dyb-dxb×dya
Now it is thus only a matter to determine either
t
oru
(you do not have to calculate both), and plug then into the formula above. SoIf the
d
in the equation (the denominator) is equal to zero, this means there is no intersection (the two lines are parallel). You can decide to alter the function and for instance returnNone
or raise an exception in such case.If you test it, for instance with a vector (1,0) offset and direction (0,1); and a vector with offset (0,2) and direction (1,1); you get the not very surprising result of: