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?

  • $\begingroup$ @PeterSheldrick Okay I think I get it with the dimensions, but I dont really get what you mean with the sphere and how to get the point on the cube. Could you further explain what to do? $\endgroup$
    – wizard003
    Jan 21, 2020 at 17:14

2 Answers 2


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.


The six faces of the cube $C$ determine six infinite planes which together partition ${\mathbb R}^3$ into $27$ compartments, one of which is $C$ itself. $6$ are quadratic prisms erected on the six faces of $C$, and extending to infinity. $12$ are $90^\circ$-wedges meeting the cube outside along an edge, and $8$ are octants originating at a vertex of the cube.

Assume $C=[-1,1]^3$ and $p=(p_1,p_2,p_3)$. The number $$n_p:=\#\bigl\{i\bigm| |p_i|>1\bigr\}$$ determines to which kind of compartment the point $p$ belongs. It is then easy to determine the nearest point on $C$: It will be $p$, if $n_p=0$, it will be the orthogonal projection of $p$ onto a face of $C$ if $n_p=1$, etcetera.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .