Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the closest point on a right rectangular prism ( 3d rectangle )

If I have a right rectangular prism with corners labeled as below.

enter image description here

and I have a random point q in 3D space how do I find the closest point on the cube to q

like image 778
bradgonesurfing Avatar asked Jun 29 '17 11:06

bradgonesurfing


1 Answers

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;
}
like image 160
bradgonesurfing Avatar answered Nov 15 '22 09:11

bradgonesurfing