如果 t1 與 t2 都在 0~1 之間,代表 P 同時在兩個線段上,也就代表兩個線段有相交。

Note

另外如果是判斷直線相交,或是直線與線段的相交,都可以用同一套公式,只是 t1 與 t2 的範圍不同而已。

程式碼

public bool Intersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d, out Vector2 p)
{
    const float Eplilon = 1e-6f;
    
    Vector2 ab = b - a;
    Vector2 cd = d - c;
 
    float det = ab.x * cd.y - cd.x * ab.y;  // Determinant
    if (Mathf.Abs(det) < Eplilon)  // Check if parallel
    {
        p = default;
        return false;
    }
 
    Vector2 ac = c - a;
    float t1 = (ac.x * cd.y - ac.y * cd.x) / det;
    float t2 = (ac.x * ab.y - ac.y * ab.x) / det;
    
    // Check if intersection lies on each segments
    if (t1 < 0f || t1 > 1f)
    {
        p = default;
        return false;
    }
 
    if (t2 < 0f || t2 > 1f)
    {
        p = default;
        return false;
    }
 
    p = a + ab * t1;
    return true;
}