如何计算交叉平面和线(Unity3d)

时间:2016-01-20 05:28:33

标签: unity3d intersection

我尝试计算交叉平面和线,但我认为得到了错误的结果。 试试这段代码(来自http://wiki.unity3d.com/index.php/3d_Math_functions):

public static bool LinePlaneIntersection(out Vector3 intersection, Vector3 linePoint, Vector3 lineVec, Vector3 planeNormal, Vector3 planePoint)
{
    float length;
    float dotNumerator;
    float dotDenominator;
    Vector3 vector;
    intersection = Vector3.zero;

    //calculate the distance between the linePoint and the line-plane intersection point
    dotNumerator = Vector3.Dot((planePoint - linePoint), planeNormal);
    dotDenominator = Vector3.Dot(lineVec, planeNormal);

    if (dotDenominator != 0.0f)
    {
        length = dotNumerator / dotDenominator;

        vector = SetVectorLength(lineVec, length);

        intersection = linePoint + vector;

        return true;
    }

    else
        return false;
}

1 个答案:

答案 0 :(得分:1)

  

但我认为结果错了。

你能更具体一点吗?

你正在使用的等式似乎是正确的;虽然我会使用lineVec.noramlized * length而不是那个奇怪的SetVectorLength函数。

线和平面交点的基本公式是线上的点x,其中值为x由下式给出:

a = (point_on_plane - point_on_line) . plane_normal
b = line_direction . plane_normal

if b is 0: the line and plane are parallel
if a is also 0: the line is exactly on the plane
otherwise: x = a / b

因此交点是:x * line_direction + line_point

这正是你的代码所做的......所以......?

您可以在此处阅读维基页面上的更多详细信息:

https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection

编辑:实际上,看起来这段代码假设如果dotDenominator为零则它们不相交;部分正确;如果dotNumerator也为零,则该线正好位于平面的顶部,并且所有点都相交,因此请将您想要的任何点作为交点(例如。planePoint)。