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

               

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

猜你喜欢

转载自blog.csdn.net/sjhfkhsf/article/details/87855696