2013-05-03 95 views
1

我有一個路徑作爲點存儲在數組列表中,我想檢查線段是否相交。由於某些未知的原因,它不起作用!儘管我正在繪製相交的形狀,但我在LogCat中沒有收到任何消息。如果有人能夠看到我做錯了什麼,或者對如何改進代碼有所建議,請詳細說明。線段之間的交點問題

// Intersection control 
    if(touchActionUp) { 

     // Loop throw all points except the last 3 
     for (int i = 0; i < points.size()-3; i++) { 
      Line line1 = new Line(points.get(i), points.get(i+1)); 

      // Begin after the line above and check all points after that 
      for (int j = i + 2; j < points.size()-1; j++) { 
       Line line2 = new Line(points.get(j), points.get(j+1)); 

       // Call method to check intersection 
       if(checkIntersection(line1, line2)) { 
        Log.i("Intersection", "Yes!"); 
       } 
      } 
     } 
    } 

並且所述方法:

// Method to check for intersection between lines 
private boolean interceptionControl(Line line1, Line line2) { 
    int x1 = line1.pointX1; 
    int x2 = line1.pointX2; 
    int x3 = line2.pointX1; 
    int x4 = line2.pointX2; 

    int y1 = line1.pointY1; 
    int y2 = line1.pointY2; 
    int y3 = line2.pointY1; 
    int y4 = line2.pointY2; 

    // Check if lines are parallel 

    int denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); 

    if(denom == 0) { // Lines are parallel 
     // ?? 
    } 

    double a = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))/denom; 
    double b = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))/denom; 

    // Check for intersection 
    if(a >= 0.0f && a <= 1.0f && b >= 0.0f && b <= 1.0f) { 
     return true; 
    } 
    return false; 
} 
+0

「它不工作」在哪種方式?錯誤?沒有檢測到交點? – sashkello 2013-05-03 15:13:56

+0

它沒有檢測到路口 – 2013-05-03 15:14:29

+0

是否測試=== denom?我沒有看到「測試」聲明 – 2013-05-03 15:16:53

回答

0

您正在使用int爲座標和它確實是這樣的整數除法(即3/2 = 1)。這可能是你除以denom的原因。您可以通過除以((double)denom)而不是簡單地將其修復爲denom

+0

謝謝,但它仍然不工作!我測試過((雙)denom)。任何其他建議? – 2013-05-03 15:24:34

+0

Mate,代碼對我來說工作得非常好,你考慮哪些點? – sashkello 2013-05-04 08:46:50