簡體   English   中英

線段相交(僅交叉,無接觸)

[英]Line Segment Intersection (Crossing only, no touching)

我嘗試找到“線段交叉”。 因此,我希望下面的函數僅在兩條線確實彼此交叉時才返回true,而不是在相同點處開始/結束時才返回true。 從我閱讀的內容來看,這似乎是一種“平凡”的數學解決方案,但是無論在何處提及,都無法以我能理解的方式進行解釋。

下面的功能可以正確檢測包括“觸摸”點在內的線段交點。 有沒有簡單的方法可以修改它以滿足我的需求?

非常感謝您的幫助!

inline double Dot(sf::Vector2f a, sf::Vector2f  b) { return (a.x*b.x) + (a.y*b.y); }
inline double PerpDot(sf::Vector2f a, sf::Vector2f b) { return (a.y*b.x) - (a.x*b.y); }

static bool LineCollision(const sf::Vector2f A1, const sf::Vector2f A2,
    const sf::Vector2f B1, const sf::Vector2f B2,
    double* out = 0)
{
    sf::Vector2f a(A2 - A1);
    sf::Vector2f b(B2 - B1);

    double f = PerpDot(a, b);
    if (!f)      // lines are parallel
        return false;

    sf::Vector2f c(B2 - A2);
    double aa = PerpDot(a, c);
    double bb = PerpDot(b, c);

    if (f < 0)
    {
        if (aa > 0)     return false;
        if (bb > 0)     return false;
        if (aa < f)     return false;
        if (bb < f)     return false;
    }
    else
    {
        if (aa < 0)     return false;
        if (bb < 0)     return false;
        if (aa > f)     return false;
        if (bb > f)     return false;
    }

    if (out)
        *out = 1.0 - (aa / f);
    return true;
}

要排除段結尾,請在所有內部if's中將嚴格比較<>更改為<=>=如下所示:

    if (aa >= 0)     return false;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM