如何判断两个矩形是否有重叠部分?(某公司校园招聘笔试试题)

做游戏的公司,自然会关注游戏中物体是否碰撞的问题。我们知道:判断两个圆是否有重叠很简单,当且仅当 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值