[英]visual c++ RECT collision
幾天前,我才剛剛開始使用Win32 GUI編程。 我正在嘗試制作一個簡單的游戲,其中我需要檢測2個對象之間的碰撞。 所以我用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;
}
我就一個問題在這里找到,它似乎像情況下工作這樣 。 但是有一個小問題,它這種情況在這里
有什么辦法可以解決這個問題? 我做錯了嗎? 我應該嘗試其他方法嗎? 任何提示都會有所幫助。
看一下API函數:
清楚地檢查一個矩形的角是否在另一個矩形內是個壞主意:
一個簡單的檢查方法是:
if (a.left >= b.right || a.right <= b.left ||
a.top >= b.bottom || a.bottom <= b.top) {
// No intersection
} else {
// Intersection
}
此解決方案無效。 您可能有兩個矩形相交,而其中任何一個頂點都不位於另一個矩形中。 例如((0,0), (10,10))
和((5,-5), (7, 15))
。 嘗試檢查其中一個矩形的邊是否與另一個矩形相交。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.