Finding the nearest (least distance) point on a cube from a point lying outside

3dgeometryoptimization

Suppose there is a given cube and a point outside of that cube. Now I want to find out the point on the cube with the least distance to the point outside of the cube.
I have found a similar post: Minimal distance to a cube in 2D and 3D from a point lying outside
But I am not interested in the distance value itself, I want to know the position of the point on the cube that satisfies the nearest distance.

Here also the image from the post above. The point p is the outside point and r is the minimal distance to the cube. But I am interested in the point at the end of r on the cube.

And also follow up question, is there an efficient way to generalize and calculate this for n-dimension hypercube?

Best Answer

First make your cube axis aligned, ie. use an (invertible) affine transformation $f:\mathbb R^3 \rightarrow \mathbb R^3$ such that the faces are all parallel to some $xy$-/$xz$-/$yz$-plane. Dont forget to apply this affine transformation to your point.

For an axis aligned box $[x_\min,x_\max]\times[y_\min,y_\max]\times[z_\min,z_\max]$ you can find the projection of a point $q = (q_x,q_y,q_z)$ outside the box by taking $p = (\mathsf{clamp}(q_x,x_\min,x_\max),\mathsf{clamp}(q_y,y_\min,y_\max),\mathsf{clamp}(q_z,z_\min,z_\max))$, where

$$\mathsf{clamp}(t,a,b) = \left\{ \begin{array}{ll}a&\text{if }t\leq a\\t & \text{if }t \in [a,b]\\ b &\text{if }b \leq t\end{array}\right.$$

Since you will likely want to have the coordinates of the projection in the original coordinate system, apply the inverse of $f$ to the point just calculated.

This should generalize to higher dimensions.