bra*_*ing 5 algorithm geometry
如果我有一个直角棱柱,角标如下。
我在 3D 空间中有一个随机点q如何找到立方体上离q最近的点
假设 C# 中存在向量类型库,其点积定义为
double Dot(Vector3 a, Vector3 b) => a.X * b.X + a.Y*b.Y + a.Z*b.Z;
Run Code Online (Sandbox Code Playgroud)
和 LengthSquared 定义为
double LengthSquared ()=> Dot(this,this);
Run Code Online (Sandbox Code Playgroud)
将点投影到超矩形的每个独立轴上以找到投影的标量参数。然后使标量参数在面的极限处饱和。然后将各分量相加即可得到答案
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;
}
Run Code Online (Sandbox Code Playgroud)