假设有矩形RECT1和RECT2、有八个顶点
1 bool test_collision__2(SDL_Rect *rect1, SDL_Rect *rect2) 2 { 3 int x1_1 = rect1->x; 4 int y1_1 = rect1->y; 5 int x1_2 = rect1->x + rect1->w; 6 int y1_2 = rect1->y; 7 int x1_3 = rect1->x; 8 int y1_3 = rect1->y + rect1->h; 9 int x1_4 = rect1->x + rect1->w;10 int y1_4 = rect1->y + rect1->h;11 12 13 14 int x2_1 = rect2->x;15 int y2_1 = rect2->y;16 int x2_2 = rect2->x + rect2->w;17 int y2_2 = rect2->y;18 int x2_3 = rect2->x;19 int y2_3 = rect2->y + rect2->h;20 int x2_4 = rect2->x + rect2->w;21 int y2_4 = rect2->y + rect2->h;22 23 // 判断矩形一的四个顶点之一是否在矩形二中24 if( (x1_1 > x2_1 && x1_1 < x2_4) && (y1_1 > y2_1 && y1_1 < y2_4) )25 {26 return true;27 }28 29 if( (x1_2 > x2_1 && x1_2 < x2_4) && (y1_2 > y2_1 && y1_2 < y2_4) )30 {31 return true;32 }33 34 if( (x1_3 > x2_1 && x1_3 < x2_4) && (y1_3 > y2_1 && y1_3 < y2_4) )35 {36 return true;37 }38 39 if( (x1_4 > x2_1 && x1_4 < x2_4) && (y1_4 > y2_1 && y1_4 < y2_4) )40 {41 return true;42 }43 44 // 判断矩形二的四个顶点之一是否在矩形一中45 46 if( (x2_1 > x1_1 && x2_1 < x1_4) && (y2_1 > y1_1 && y2_1 < y1_4) )47 {48 return true;49 }50 51 if( (x2_2 > x1_1 && x2_2 < x1_4) && (y2_2 > y1_1 && y2_2 < y1_4) )52 {53 return true;54 }55 56 if( (x2_3 > x1_1 && x2_3 < x1_4) && (y2_3 > y1_1 && y2_3 < y1_4) )57 {58 return true;59 }60 61 if( (x2_4 > x1_1 && x2_4 < x1_4) && (y2_4 > y1_1 && y2_4 < y1_4) )62 {63 return true;64 }65 66 67 68 return false;69 }
判断的方法狠简单、如果矩形相交、那么肯定存在至少一个矩形的顶点存在于另一个矩形内、所谓在矩形内、也就是这个顶点的坐标的X值和Y值分别位于矩形的左上角(x_min, y_min)坐标与右下角(x_max, y_max)坐标之间、也就当x_min < x < x_max且y_min < y < y_max时、这个顶点存在于
实际上、上面这么描述并不对、这个算法充其量就是边界算法、因为下面这种情况是两个矩形的四个顶点都不矩形中、但因为这种是特殊的简化情况、一旦碰壁就停止、那么也没什么所谓、如果是需要计算碰壁后能穿透的情况下、这种蛮力算法就无能为力了
假设有矩形1的左上角点(x1,y1)和右下角点(x2, y2)、和矩形2从左上角点(x3,y3)和右下角点(x4,y4)、可根据以下算法判断是否相交
优化算法:
1 // 判断两矩形是否相交、原理狠简单、如果相交、肯定其中一个矩形的顶点在另一个顶点内、 2 bool test_collision(SDL_Rect *rect1, SDL_Rect *rect2) 3 { 4 int x1 = rect1->x; 5 int y1 = rect1->y; 6 int x2 = rect1->x + rect1->w; 7 int y2 = rect1->y + rect1->h; 8 9 int x3 = rect2->x;10 int y3 = rect2->y;11 int x4 = rect2->x + rect2->w;12 int y4 = rect2->y + rect2->h;13 14 return ( ( (x1 >=x3 && x1 < x4) || (x3 >= x1 && x3 <= x2) ) &&15 ( (y1 >=y3 && y1 < y4) || (y3 >= y1 && y3 <= y2) ) ) ? true : false;16 17 }
参考资料: