检测矩形和圆形的c++代码
时间: 2023-08-28 20:26:38 浏览: 49
以下是一个简单的检测矩形和圆形相交的 C++ 代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
int x, y;
};
bool isCircleIntersectRect(Point circleCenter, int radius, Point rectPos, int rectWidth, int rectHeight) {
// 计算圆心到矩形边界的最短距离
int distX = abs(circleCenter.x - rectPos.x - rectWidth / 2);
int distY = abs(circleCenter.y - rectPos.y - rectHeight / 2);
// 如果圆心到矩形边界的距离大于圆的半径,则不相交
if (distX > (rectWidth / 2 + radius)) return false;
if (distY > (rectHeight / 2 + radius)) return false;
// 如果圆心到矩形边界的距离小于等于圆的半径,则相交
if (distX <= (rectWidth / 2)) return true;
if (distY <= (rectHeight / 2)) return true;
// 计算圆心到矩形角落的距离
int dx = distX - rectWidth / 2;
int dy = distY - rectHeight / 2;
return (dx * dx + dy * dy <= (radius * radius));
}
int main() {
Point circleCenter = {10, 10};
int radius = 5;
Point rectPos = {0, 0};
int rectWidth = 10, rectHeight = 10;
if (isCircleIntersectRect(circleCenter, radius, rectPos, rectWidth, rectHeight)) {
cout << "Circle and rectangle intersect!" << endl;
} else {
cout << "Circle and rectangle do not intersect!" << endl;
}
return 0;
}
```
在这里,我们定义了一个 `Point` 结构体,用于存储点的坐标。`isCircleIntersectRect()` 函数用于检测圆形和矩形是否相交。如果相交,则返回 `true`,否则返回 `false`。
我们首先计算圆心到矩形边界的最短距离。如果这个距离大于圆的半径,则两者不相交。如果这个距离小于等于圆的半径,则两者相交。
如果圆心到矩形边界的距离小于等于矩形宽度或高度的一半,则两者相交。
最后,我们计算圆心到矩形角落的距离。如果这个距离小于等于圆的半径,则两者相交。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)