How do I determine whether or not two lines intersect, and if they do, at what x,y point?
相关问题
- How to determine +/- sign when calculating diagona
- Union of many (more than two) polygons without hol
- Is there a way to rotate text around (or inside) a
- Filling rectangle with points pattern
- Unity Intersections Mask
相关文章
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- SVG circle starting point
- How to calculate end points of perpendicular line
- Calculate the eccentricity of ellipses
- Draw a rectangle arround a polygon when given in c
- How to determine a diagonal is in or out of a conc
This based on Gareth Ree's answer. It also returns the overlap of the line segments if they do. Coded in C++, V is a simple vector class. Where the cross product of two vectors in 2D returns a single scalar. It was tested and passed by my schools automatic testing system.
FWIW, the following function (in C) both detects line intersections and determines the intersection point. It is based on an algorithm in Andre LeMothe's "Tricks of the Windows Game Programming Gurus". It's not dissimilar to some of the algorithm's in other answers (e.g. Gareth's). LeMothe then uses Cramer's Rule (don't ask me) to solve the equations themselves.
I can attest that it works in my feeble asteroids clone, and seems to deal correctly with the edge cases described in other answers by Elemental, Dan and Wodzu. It's also probably faster than the code posted by KingNestor because it's all multiplication and division, no square roots!
I guess there's some potential for divide by zero in there, though it hasn't been an issue in my case. Easy enough to modify to avoid the crash anyway.
BTW, I must say that in LeMothe's book, though he apparently gets the algorithm right, the concrete example he shows plugs in the wrong numbers and does calculations wrong. For example:
That confused me for hours. :(
I think there is a much much simpler solution for this problem. I came up with another idea today and it seems to work just fine (at least in 2D for now). All you have to do, is to calculate the intersection between two lines, then check if the calculated intersection point is within the boundig boxes of both line segments. If it is, the line segments intersect. That's it.
EDIT:
This is how I calculate the intersection (I don't know anymore where I found this code snippet)
comes from
and this is my (simplified for the purpose of the answer) BoundingBox class:
This solution may help
I tried lot of ways and then I decided to write my own. So here it is:
Based on these two formulas: (I simplified them from equation of lines and other formulas)
A C++ program to check if two given line segments intersect