Determine if two rectangles overlap each other?

前端 未结 23 1153
礼貌的吻别
礼貌的吻别 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:03

    For those of you who are using center points and half sizes for their rectangle data, instead of the typical x,y,w,h, or x0,y0,x1,x1, here's how you can do it:

    #include  // for fabsf(float)
    
    struct Rectangle
    {
        float centerX, centerY, halfWidth, halfHeight;
    };
    
    bool isRectangleOverlapping(const Rectangle &a, const Rectangle &b)
    {
        return (fabsf(a.centerX - b.centerX) <= (a.halfWidth + b.halfWidth)) &&
               (fabsf(a.centerY - b.centerY) <= (a.halfHeight + b.halfHeight)); 
    }
    

提交回复
热议问题