检查两条 Vector3 线何时相交 - Unity3D

Check when two Vector3 lines intersect - Unity3D

我想知道四个 Vector 3 位置何时相交,如图所示,从点到点 a1 到 a2 和 b1 到 b2 如果它们从各自的位置彼此相交。有谁知道如何做到这一点?

Unity 社区 wiki a page of math functions 包含对此非常有用的过程。复制(并稍作编辑)如下:

public static bool LineLineIntersection(out Vector3 intersection, Vector3 linePoint1,
        Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){

    Vector3 lineVec3 = linePoint2 - linePoint1;
    Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2);
    Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2);

    float planarFactor = Vector3.Dot(lineVec3, crossVec1and2);

    //is coplanar, and not parallel
    if( Mathf.Abs(planarFactor) < 0.0001f 
            && crossVec1and2.sqrMagnitude > 0.0001f)
    {
        float s = Vector3.Dot(crossVec3and2, crossVec1and2) 
                / crossVec1and2.sqrMagnitude;
        intersection = linePoint1 + (lineVec1 * s);
        return true;
    }
    else
    {
        intersection = Vector3.zero;
        return false;
    }
}

因此,在您的情况下,您可以使用它,然后检查交点是否在 a1 和 a2 以及 b1 和 b2 之间:

Vector3 intersection;
Vector3 aDiff = a2-a1;
Vector3 bDiff = b2-b1;
if (LineLineIntersection(out intersection, a1, aDiff, b1, bDiff))
{
    float aSqrMagnitude = aDiff.sqrMagnitude;
    float bSqrMagnitude = bDiff.sqrMagnitude;

    if (    (intersection - a1).sqrMagnitude <= aSqrMagnitude  
         && (intersection - a2).sqrMagnitude <= aSqrMagnitude  
         && (intersection - b1).sqrMagnitude <= bSqrMagnitude 
         && (intersection - b2).sqrMagnitude <= bSqrMagnitude)
    {
        // there is an intersection between the two segments and 
        //   it is at intersection
    }
}