Basically, line segments' intersection is a mathematical concept. To detect the intersection of two line segments, find their intersection points. For 2D games, it is very helpful when an explosion animation appears at a position where the two lines intersect; for example, two laser shoots collide. The line segments' intersection can also help you to make a decision in pool games as a guideline, especially for beginners. In this recipe, you will learn how to detect the line segments' intersection.
To define the two line segments, we need the following two formulae:
If you put in 0
for U, you'll get the start point, if you put in 1
, you'll get the end point.
With the two equations, if the intersection happens between the two line segments:
The equation could be rewritten as follows:
In order to get the Ua
and Ub
values, we need two equations. The previous equation could also be written using x and y factors of the points:
You can use the...