To get the point where two lines intersect, we will do some maths. To the mathematicians who will come across this post, I’m truly sorry for the heart attacks or strokes you may experience by reading this post.
Ok, let’s take a look on the figure:
Figure 1
First, sorry, I was too lazy to make a proper figure using computer tools so I just put a scan. XD
Next, here are the definitions:
& : the two lines,
, : the arbitrary starting points of the two lines,
, : the arbitrary points which tells the direction of the two lines,
: the intersection point,
: the origin point.
Kewl. Now, what we want is the intersection point between those two lines. In other words, we want to know the position which starts from either lines’ arbitrary starting point, added by the direction of the line multiplied by a scalar value. So in our figure 1, the position is:
the position added by the components of multiplied by an unknown which I named
the position added by the components of multiplied by an unknown which I named
In this case, it is clear that so it will be easy to check if our final formula is correct. 🙂
At the point of intersection, we know that:
… which gives us:
But we can’t use this statement exactly like this to solve our equation as we cannot multiply and divide vectors in this raw format. Also we need to reduce the unkowns count to 1. So we will separate our equation into two equations with the magic of matrices (which I don’t understand well at the moment), one for the x component and one for the y:
To make our equation more readable, we will use some shorthands:
… so:
From this point, we can reduce the unknown count. In my case, I have chosen to keep instead of :
And finally, you have to check if . This will happen if your two lines are parallel or if there is one line defined as a point such as or ; no solution exists in those cases.
Commentaires
2 réponses à “Unity3D.tips[2]: Intersection point between two lines in 2D”
Nice explanation. Thanks for the blog, i was scratching my head for a while before reading the blog.
Thanks so much. It saved my day.