2010-12-04 60 views
-1

我有一個CSharp項目中呈現矩形的兩個對象。現在我想計算一個對象是否與另一個對象相交。對象不能旋轉。交集算法

我有以下方法:

getX(); 
getY(); 
getWidth(); 
getHeight(); 
+0

重複這個問題:http://stackoverflow.com/questions/306316/determine- if-two-rectangles-overlap-each-other – 2010-12-04 16:58:40

回答

2

雖然這技術上,其他問題的重複,我建議比被張貼有沒有更好的解決方案。

我會看它的方式將從邊界框的角度來看。如果邊框比高度,比寬度之和瘦的和短的,他們必須相交:

// assume we have a class with a constructor like so... 
class Rect 
{ 
    ... 
    void Rect(int top, int left, int bottom, int right) { ... } 
    ... 
} 

... 

private Rect GetBoundingRect(Rect r1, Rect r2) 
{ 
    int left = min(r1.getX(), r2.getX()); 
    int right = max(r1.getX()+r1.getWidth(), r2.getX()+r2.getWidth()); 
    int top = min(r1.getY(), r2.getY()); 
    int bottom = max(r1.getY()+r1.getHeight(), r2.getY()+r2.getHeight()); 
    return new Rect(top, left, bottom, right); 
} 

private bool CheckIfIntersect(Rect r1, Rect r2) 
{ 
    Rect bound = GetBoundingRect(r1,r2); 
    return (bound.getWidth() < r1.getWidth() + r2.getWidth()) && 
      (bound.getHeight() < r1.getHeight() + r2.getHeight()); 
}