Detecting Line Intersection
- In this project, I solve the problem of detecting if two line segments touch each other
- This is useful when you want to make a video game and you want to detect if two objects touch, and those objects are lines or are made up of lines.
- My solution has two steps:
- Step 1: I assume that both lines are infinitely long, and I find the point of intersection.
Given a line segment with end points (x1, y1) and (x2, y2), we can express the equation of the line as y = mx + b, where m is the slope of the line which is equal to (y2 - y1) / (x2 - x1), and b is the y-intercept and is equal to y1 - mx1. Once you find the equation for two line segments, you can find their intersection point by solving for x and y.
- Step 2: I check if the point of intersection is on both line segments.
To figure out if a point is on a line segment, you can use the pythagorous theorom to find the distance between the point and both of the end points of the line segment. Then, you add both of the distances together and see if that is equal to the distance of one end point to the other. If it is, the point is on the line.
Drag the balls to change the position of the lines. The line segments turn green to indicate they intersect.