2013-03-21 49 views
1

我剛剛開始使用Win32 GUI編程,幾天前。我試圖做一個簡單的遊戲,我需要檢測兩個對象之間的碰撞。 所以我用RECT結構visual C++ RECT碰撞

爲檢測做了我字符如果他們碰撞我已經使用:

// Returns 1 if the point (x, y) lies within the rectangle, 0 otherwise 
int is_point_in_rectangle(RECT r, int x, int y) { 
    if ((r.left <= x && r.right >= x) && 
     (r.bottom <= y && r.top >= y)) 
     return 1; 
    return 0; 
} 

// Returns 1 if the rectangles overlap, 0 otherwise 
int do_rectangles_intersect(RECT a, RECT b) { 
    if (is_point_in_rectangle(a, b.left , b.top ) || 
     is_point_in_rectangle(a, b.right, b.top ) || 
     is_point_in_rectangle(a, b.left , b.bottom) || 
     is_point_in_rectangle(a, b.right, b.bottom)) 
     return 1; 
    if (is_point_in_rectangle(b, a.left , a.top ) || 
     is_point_in_rectangle(b, a.right, a.top ) || 
     is_point_in_rectangle(b, a.left , a.bottom) || 
     is_point_in_rectangle(b, a.right, a.bottom)) 
     return 1; 
    return 0; 
} 

這我就一個問題在這裏找到,它似乎像this情況下工作。但是這個情況有個小問題here

有沒有什麼辦法解決這個問題?我做錯了嗎?我應該嘗試一種不同的方法嗎? 任何提示將有所幫助。

回答

1

顯然檢查,如果一個長方形的角落裏,另一個是一個壞主意:

Intersecting rectangles

一個簡單的方法做檢查,而不是:

if (a.left >= b.right || a.right <= b.left || 
    a.top >= b.bottom || a.bottom <= b.top) { 

    // No intersection 

} else { 

    // Intersection 

} 
+0

謝謝你,我結束了在我最初使用的函數的末尾加上這個,並且它似乎完成了這項工作 – 2013-03-21 15:18:08

+0

這段代碼完成了整個檢查,它可以完全替代**該函數。試着花一些時間用紙和鉛筆來理解爲什麼它足以應付所有可能的情況。 – 6502 2013-03-21 15:34:38

+0

我只是測試它,它似乎並沒有在這種情況下工作http://puu.sh/2lrXw – 2013-03-21 17:25:35

0

此解決方案無效。你可能有兩個矩形相交,而沒有任何一個頂點位於另一個頂點。例如((0,0), (10,10))((5,-5), (7, 15))。嘗試檢查其中一個矩形的是否與另一個矩形相交。