做游戏的公司,自然会关注游戏中物体是否碰撞的问题。我们知道:判断两个圆是否有重叠很简单,当且仅当 r1 + r2 <= d 时,两个圆有重叠部分,矩形可以看成是特殊的圆,一个矩形存在垂直方向和水平方向两个半径,基于该思路,写出算法代码如下:(矩形不会倾斜)
#include<iostream>
#include<cmath>
using namespace std;
typedef struct rectangle
{
float centerX;
float centerY;
float width;
float height;
}Rectangle;
bool areTwoRectsOverlapped(Rectangle rect1, Rectangle rect2)
{
float verticalDistance; //垂直距离
float horizontalDistance; //水平距离
verticalDistance = fabs(rect1.centerX - rect2.centerX);
horizontalDistance = fabs(rect1.centerY - rect2.centerY);
float verticalThreshold; //两矩形分离的垂直临界值
float horizontalThreshold; //两矩形分离的水平临界值
verticalThreshold = (rect1.height + rect2.height)/2;
horizontalThreshold = (rect1.width + rect2.height)/2;
if(verticalDistance > verticalThreshold || horizontalDistance > horizontalThreshold)
return false;
return true;
}
假设是确保有效的 RECT,不是无效的
RECT r1, r2;
...
RECT rCommon;
rCommon.left = max(r1.left, r2.left);
rCommon.top = max(r1.top, r2.top);
rCommon.right = min(r1.right, r2.right);
rCommon.bottom = min(r1.bottom, r2.bottom);
这个 rCommon 是这两个矩形的交集,判断交集部分是否是有效的矩形就可以了
int main()
{
Rectangle rect1 = {0.0, 0.0, 20.0, 10};
Rectangle rect2 = {6.0, 6.0, 2.1, 1.9};
if(areTwoRectsOverlapped(rect1, rect2))
cout << "overlapped" << endl;
else
cout << "not overlapped" << endl;
return 0;
}
http://www.codeproject.com/KB/recipes/Wykobi.aspx