用c++写一段矩形碰撞检测算法
时间: 2023-05-28 13:04:58 浏览: 71
以下是一个简单的矩形碰撞检测算法,使用 C 语言编写:
```c
#include <stdio.h>
typedef struct {
int x, y, width, height;
} Rect;
/**
* 判断矩形 A 和矩形 B 是否相交
*/
int rectIntersect(Rect A, Rect B) {
if (A.x + A.width < B.x || A.x > B.x + B.width ||
A.y + A.height < B.y || A.y > B.y + B.height) {
return 0;
} else {
return 1;
}
}
int main() {
Rect rect1 = {0, 0, 10, 10};
Rect rect2 = {5, 5, 10, 10};
if (rectIntersect(rect1, rect2)) {
printf("矩形相交\n");
} else {
printf("矩形不相交\n");
}
return 0;
}
```
该算法使用了一个 `Rect` 结构体来表示矩形,包括矩形的左上角坐标 `(x, y)` 和宽高 `width`, `height`。`rectIntersect` 函数用于判断两个矩形是否相交,如果相交返回 1,否则返回 0。具体判断方法是:如果矩形 A 的右侧在矩形 B 的左侧,或者矩形 A 的左侧在矩形 B 的右侧,或者矩形 A 的下方在矩形 B 的上方,或者矩形 A 的上方在矩形 B 的下方,则两个矩形不相交;否则相交。最后的 `main` 函数测试了两个矩形的相交情况并输出结果。