Determine if two rectangles overlap each other?

前端 未结 23 1361
礼貌的吻别
礼貌的吻别 2020-11-22 04:09

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectang

23条回答
  •  星月不相逢
    2020-11-22 05:02

    It is easier to check if a rectangle is completly outside the other, so if it is either

    on the left...

    (r1.x + r1.width < r2.x)
    

    or on the right...

    (r1.x > r2.x + r2.width)
    

    or on top...

    (r1.y + r1.height < r2.y)
    

    or on the bottom...

    (r1.y > r2.y + r2.height)
    

    of the second rectangle, it cannot possibly collide with it. So to have a function that returns a Boolean saying weather the rectangles collide, we simply combine the conditions by logical ORs and negate the result:

    function checkOverlap(r1, r2) : Boolean
    { 
        return !(r1.x + r1.width < r2.x || r1.y + r1.height < r2.y || r1.x > r2.x + r2.width || r1.y > r2.y + r2.height);
    }
    

    To already receive a positive result when touching only, we can change the "<" and ">" by "<=" and ">=".

提交回复
热议问题