[Math] How to check if a 3D line segment intersects a cylinder

3dgeometry

I have developed a check for a 2D case of a circle intersecting a 2D line segment, however there is a particular case that I can't figure out how to extend to 3D:

If one endpoint on the 3D line segment is inside the 2D projected circle, but above the cylinder, and the other endpoint is outside of the circle, but below the cylinder, how do I check if the line segment crossed the cylinder?

enter image description here

Best Answer

Let's say that each horizontal cross-section of the cylinder (a circle) has a radius of $r$. That means that on any slice of the cylinder, we have a circle of the form

$$x_c^2+y_c^2=r^2 \text{(Eqn.1)}$$

Now let's write the equation of the line as if we were looking at the whole thing from above (i.e. ignoring it in the z-direction and writing $y_l$ as a function of $x_l$). It would have an apparent equation of the form $$y_l=mx_l+b \text{(Eqn 2)}$$ Now, if the line crosses the circle at at least one point, then $y_c=y_l$ and $x_c=x_l$. We substitute $y_l$ into $\text {Eqn 1}$ and $x_l$ into $\text {Eqn 1}$, making it

$$x_l^2+(mx_l+b)^2=r^2 \text{(Eqn.3)}$$ Now we can solve for $x_l$. We can plug that into $\text {Eqn 2}$ to find $y_l$, and because we know $y_c=y_l$ and $x_c=x_l$, we can solve for the other variables. If we know the location of $A$ and $B$, we can then find the position of that point in 3-dimensional space.