C#中线段与轴对齐框的交点

我正在寻找一种算法来确定线段和轴对齐框之间的近交点和远交点。

这是我的方法定义:

public static Point3D[] IntersectionOfLineSegmentWithAxisAlignedBox( Point3D rayBegin, Point3D rayEnd, Point3D boxCenter, Size3D boxSize) 

如果线段不与框相交,则该方法应返回空的Point3D数组。

从我到目前为止的研究中,我发现了一些高度优化算法的研究论文,但它们似乎都是用C ++编写的,需要将多个长类文件转换为C#。 对于我的目的,一些相当有效的东西,易于理解的人获得点产品和交叉产品,以及简单/短期将是首选。

这是我最终使用的内容:

 public static List IntersectionOfLineSegmentWithAxisAlignedBox( Point3D segmentBegin, Point3D segmentEnd, Point3D boxCenter, Size3D boxSize) { var beginToEnd = segmentEnd - segmentBegin; var minToMax = new Vector3D(boxSize.X, boxSize.Y, boxSize.Z); var min = boxCenter - minToMax / 2; var max = boxCenter + minToMax / 2; var beginToMin = min - segmentBegin; var beginToMax = max - segmentBegin; var tNear = double.MinValue; var tFar = double.MaxValue; var intersections = new List(); foreach (Axis axis in Enum.GetValues(typeof(Axis))) { if (beginToEnd.GetCoordinate(axis) == 0) // parallel { if (beginToMin.GetCoordinate(axis) > 0 || beginToMax.GetCoordinate(axis) < 0) return intersections; // segment is not between planes } else { var t1 = beginToMin.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis); var t2 = beginToMax.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis); var tMin = Math.Min(t1, t2); var tMax = Math.Max(t1, t2); if (tMin > tNear) tNear = tMin; if (tMax < tFar) tFar = tMax; if (tNear > tFar || tFar < 0) return intersections; } } if (tNear >= 0 && tNear <= 1) intersections.Add(segmentBegin + beginToEnd * tNear); if (tFar >= 0 && tFar <= 1) intersections.Add(segmentBegin + beginToEnd * tFar); return intersections; } 

 public enum Axis { X, Y, Z } 

 public static double GetCoordinate(this Point3D point, Axis axis) { switch (axis) { case Axis.X: return point.X; case Axis.Y: return point.Y; case Axis.Z: return point.Z; default: throw new ArgumentException(); } } public static double GetCoordinate(this Vector3D vector, Axis axis) { switch (axis) { case Axis.X: return vector.X; case Axis.Y: return vector.Y; case Axis.Z: return vector.Z; default: throw new ArgumentException(); } } 

好吧,对于一个轴对齐的框,它非常简单:你必须找到你的光线与6个平面的交点(由方框面定义),然后检查你发现的点对照顶点坐标限制。