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

               

         做游戏的公司,自然会关注游戏中物体是否碰撞的问题。我们知道:判断两个圆是否有重叠很简单,当且仅当 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)/2if(verticalDistance > verticalThreshold || horizontalDistance > horizontalThreshold)  return falsereturn true;}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" << endlelse     cout << "not overlapped" << endlreturn 0;}


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 1
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sjhfkhsf

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值