2017-06-11 54 views
0

我試圖找到「線段交叉點」。所以我希望下面的函數只有在兩條線互相交叉時才返回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; 
} 

回答

0

要排除區段末端,更改所有內部if's嚴格比較<><=>=這樣的:

if (aa >= 0)  return false; 
+0

非常感謝,完美的作品! – user3808217

+0

我認爲比較精確相等的浮點數不是好主意 –

+0

@ivan kuklin如果您的意思是比較某些容差 - 給定的算法不能正確使用容差來處理數字穩定性問題。有特殊的幾何。算法來克服這些問題(如果它很重要)。 – MBo