Given a sphere $S(c,r)$, $c$ being the center point $(x,y,z)$ and $r$ being the radius, there is a point $p(x', y', z')$ which is either inside or outside $S$.
I want to find the point $q$ such that $q$ is on $S$ and $|pq|$ is minimum. Where $|pq|$ denotes the Euclidean distance between $p$ and $q$.
I tried to create a ray that starts from $c$ and passes through $p$ and find the intersection of the ray with the sphere.
However, since I'm implementing a code for this problem, I could not get over it with step by step. Could you please help me?
Known: $r, C=\langle x_c, y_c, z_c\rangle, P=\langle x_p, y_p, z_p\rangle$
Unknown: $Q=\langle \color{blue}{x_q, y_q, z_q}\rangle: Q\in S(C, r)\bigwedge \overline{CQ} \parallel \overline{CP}$
Use the similarity of triangles to assert the equivalence of the following ratios: $$\begin{align} \frac{|CP|}{|CQ|} & =\frac{\sqrt{(x_p-x_c)^2+(y_p-y_c)^2+(z_p-z_c)^2}}{r}\\ ~ & =\frac{x_p-x_c}{\color{blue}{x_q}-x_c}\\ ~ & =\frac{y_p-y_c}{\color{blue}{y_q}-y_c}\\ ~ & =\frac{z_p-z_c}{\color{blue}{z_q}-z_c} \\ \therefore \color{blue}{x_q} & = x_c +\frac{ r(x_p-x_c)}{\sqrt{(x_p-x_c)^2+(y_p-y_c)^2+(z_p-z_c)^2}} \\ \color{blue}{y_q} & = y_c +\frac{ r(y_p-y_c)}{\sqrt{(x_p-x_c)^2+(y_p-y_c)^2+(z_p-z_c)^2}} \\ \color{blue}{z_q} & = z_c +\frac{ r(z_p-z_c)}{\sqrt{(x_p-x_c)^2+(y_p-y_c)^2+(z_p-z_c)^2}} \end{align}$$