I am working on the following problem:
I have a cylinder (of which I know: the radius $r_c$ and points $P_0=(x_0,y_0,z_0), P_1=(x_1,y_1,z_1)$ at the center of the two bases) and a sphere (of which I know: the center $S=(x_s,y_s,z_s)$ and the radius $r_S$), and I have to design an algorithm to check whether the sphere and the cylinder collide.
So far, I have started with a simpler problem: I check whether the sphere collides with the segment $\overline{P_0P_1}$. What I have done is:
- I check if the projection of $S$ falls over $\overline{P_0P_1}$. If it does, I compute the euclidean distance between $\overline{P_0P_1}$ and $S$ and check whether it is less than $r_S$.
- Otherwise, I check which point between $P_0$ and $P_1$ is nearer to $S$, I compute that distance and check whether it is less than $r_S$.
Implying this works, how do I extend this version to check wether the sphere collides with the cylinder?
The centerline of the cylinder is given by $$\boldsymbol{x}=\boldsymbol{p}_0+\mu\left[\boldsymbol{p}_1-\boldsymbol{p}_0 \right] \quad \mu\in[0,1].$$
Let us call the center of the sphere $\boldsymbol{x}_\text{Sphere}$. Now let us determine the minimum of the squared distance between the center of the sphere and the centerline by
$$\mu_\text{min} =\text{argmin} ||\boldsymbol{x}_\text{Sphere}-\boldsymbol{x}||^2.$$
Then we calculate the minimal distance as $d_\text{min}=||\boldsymbol{x}_\text{Sphere}-\boldsymbol{x}(\mu_\text{min})||.$ If $\mu \in [0,1]$ and $d_\text{min}\leq r_\text{Sphere}+r_\text{Cylinder}$ we will have a collsion (touch for equality) of the sphere and the surface of the cylinder. For the top and bottom we will need a different strategy. But we could start by calculating the range of possible values of $\mu \in [-\Delta\mu,1+\Delta \mu]$. The parameter $\Delta \mu$ is determined by solving for $\mu$ in the centerline quation for $$\boldsymbol{x}=\boldsymbol{p_1}+r_\text{Sphere}\dfrac{\boldsymbol{p}_1-\boldsymbol{p}_0}{||\boldsymbol{p}_1-\boldsymbol{p}_0||}.$$
This corresponds to the situation when the sphere is placed on the top of the cylinder (I assume that $\boldsymbol{p}_1$ is at the center of the top). The solution is given by
$$\mu = 1 + \dfrac{r_\text{Sphere}}{||\boldsymbol{p}_1-\boldsymbol{p}_0||}$$ By this we see that $\Delta \mu = \dfrac{r_\text{Sphere}}{||\boldsymbol{p}_1-\boldsymbol{p}_0||}$.
If your $\mu_\text{min} \notin [-\Delta\mu,1+\Delta \mu]$ we can rule out any intersection. What needs to be elaborated more detailed is the case in which $\mu_\text{min} \in [-\Delta\mu,0) \cup (1,1+\Delta \mu]$.