计算两条线段是否相交

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容