If I have a right rectangular prism with corners labeled as below.
and I have a random point q in 3D space how do I find the closest point on the cube to q
Assuming the presence of a library of Vector types in C# with dot product defined as
double Dot(Vector3 a, Vector3 b) => a.X * b.X + a.Y*b.Y + a.Z*b.Z;
and LengthSquared defined as
double LengthSquared ()=> Dot(this,this);
Project the point onto each independant axis of the hyper rectangle to find the scalar parameters of the projection. Then saturate the scalar parameters at the limit of the faces. Then sum the components to get the answer
public Vector3 ClosestPointTo
(Vector3 q, Vector3 origin, Vector3 v100, Vector3 v010, Vector3 v001)
{
var px = v100;
var py = v010;
var pz = v001;
var vx = (px - origin);
var vy = (py - origin);
var vz = (pz - origin);
var tx = Vector3.Dot( q - origin, vx ) / vx.LengthSquared();
var ty = Vector3.Dot( q - origin, vy ) / vy.LengthSquared();
var tz = Vector3.Dot( q - origin, vz ) / vz.LengthSquared();
tx = tx < 0 ? 0 : tx > 1 ? 1 : tx;
ty = ty < 0 ? 0 : ty > 1 ? 1 : ty;
tz = tz < 0 ? 0 : tz > 1 ? 1 : tz;
var p = tx * vx + ty * vy + tz * vz + origin;
return p;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With