计算两条线段是否相交

UE4的SegmentIntersection2D函数:

    /**
     * Returns true if there is an intersection between the segment specified by SegmentStartA and SegmentEndA, and
     * the segment specified by SegmentStartB and SegmentEndB, in 2D space. If there is an intersection, the point is placed in out_IntersectionPoint
     * @param SegmentStartA - start point of first segment
     * @param SegmentEndA   - end point of first segment
     * @param SegmentStartB - start point of second segment
     * @param SegmentEndB   - end point of second segment
     * @param out_IntersectionPoint - out var for the intersection point (if any)
     * @return true if intersection occurred
     */
bool FMath::SegmentIntersection2D(const FVector& SegmentStartA, const FVector& SegmentEndA, const FVector& SegmentStartB, const FVector& SegmentEndB, FVector& out_IntersectionPoint)
{
    const FVector VectorA = SegmentEndA - SegmentStartA;
    const FVector VectorB = SegmentEndB - SegmentStartB;

    const float S = (-VectorA.Y * (SegmentStartA.X - SegmentStartB.X) + VectorA.X * (SegmentStartA.Y - SegmentStartB.Y)) / (-VectorB.X * VectorA.Y + VectorA.X * VectorB.Y);
    const float T = (VectorB.X * (SegmentStartA.Y - SegmentStartB.Y) - VectorB.Y * (SegmentStartA.X - SegmentStartB.X)) / (-VectorB.X * VectorA.Y + VectorA.X * VectorB.Y);

    const bool bIntersects = (S >= 0 && S <= 1 && T >= 0 && T <= 1);

    if (bIntersects)
    {
        out_IntersectionPoint.X = SegmentStartA.X + (T * VectorA.X);
        out_IntersectionPoint.Y = SegmentStartA.Y + (T * VectorA.Y);
        out_IntersectionPoint.Z = SegmentStartA.Z + (T * VectorA.Z);
    }

    return bIntersects;
}
两线相交.jpg

你可能感兴趣的:(计算两条线段是否相交)