将Python转换为Unity C# - 数学或如何在三维空间中找到两条斜线之间的最短距离
1 个回答
1
你不需要重新编写这些方法,因为已经有相应的内置方法可以使用。
比如,要计算两个三维向量之间的距离,你可以使用 Vector3.Distance
(Unity文档)。
float distance = Vector3.Distance(someVector, anotherVector);
如果你想找到两个最接近的点,你也可以使用其他向量方法来实现。
下面是一个示例,展示如何使用这些方法找到两条不同直线上的最近点(来自Unity维基)。这个方法仍然使用行列式来进行计算。要理解为什么这样有效,你需要了解一些基本的线性代数知识,特别是关于向量的部分。
//Two non-parallel lines which may or may not touch each other have a point on each line which are closest
//to each other. This function finds those two points. If the lines are not parallel, the function
//outputs true, otherwise false.
public static bool ClosestPointsOnTwoLines(out Vector3 closestPointLine1, out Vector3 closestPointLine2, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){
closestPointLine1 = Vector3.zero;
closestPointLine2 = Vector3.zero;
float a = Vector3.Dot(lineVec1, lineVec1);
float b = Vector3.Dot(lineVec1, lineVec2);
float e = Vector3.Dot(lineVec2, lineVec2);
float d = a*e - b*b;
//lines are not parallel
if(d != 0.0f){
Vector3 r = linePoint1 - linePoint2;
float c = Vector3.Dot(lineVec1, r);
float f = Vector3.Dot(lineVec2, r);
float s = (b*f - c*e) / d;
float t = (a*f - c*b) / d;
closestPointLine1 = linePoint1 + lineVec1 * s;
closestPointLine2 = linePoint2 + lineVec2 * t;
return true;
}
else{
return false;
}
}