Consider all points on a lined defined as s+t*v, where s is a single point on the line, v is the direction of the line, and t is a parameter that produces points along the line. In your code, where you have two points, you can just define s=p0 and v=p1-p0. If t=0, then p=p0; if t=1, then p=p1, and so on.
You want to find the intersection point between two line segments, which is a point common to two line segments. Thus, you have the two lines
- s0 + t0 * v0, where s0 = p0 and v0 = p1-p0 from your code, and
- s1 + t1 * v1, where s0 = p2 and v0 = p3-p2 from your code.
Find a common point along the two lines by solving for t0 and/or t1 from
- ?s0 + t0 * v0 = s1 + t1 * v1
This is a normal linear equation system, so rearrange and reformulate the problem on matrix form.
- t0 * v0 - t1 * v1 = s1 - s0
- [v0, -v1] * [t0, t1]T = s1 - s0
Note that I assume column vectors here, and that the V-matrix is a 2-by-2 matrix where the two vectors v0 and v1 are the columns of the V-matrix. Finally, solve for t0 and t1.
- [t0, t1]T = [v0, -v1]-1 * (s1 - s0)
When you have t0 and t1, just plug any of them back into the corresponding lines to find the intersection point. Both of them will produce the same point.
Now that we have the theory, you can identify the maths with the code:
- My direction vectors v0 and v1 corresponds to your s1 and s2.
- My (s1 - s0) corresponds to your u, although there is a sign difference here that will be cancelled later, so no worries.
- Your ip is the determinant of my [v0, -v1]-1.
- Your s and t are the x and y coordinates of the multiplication of my V-matrix and (s1 - s0).
- Your i being assigned inside the if-statements is when you plug one of the t's into its corresponding line equation to produce the intersection point.
- The first if-statement checks if the resulting points are outside of the two line segments bounded by the two points. That happens when t<0 or when t>1. Remove that if-statement if you want the lines to extend indefinitely.
The theory above to find the intersection point is equally valid for 3-dimensional lines as well. It will, however, find the points along the two lines that are closest to each other, and you need to find some other method to invert the V-matrix since it's no longer square; for example, the pseudo-inverse.