Determine if two rectangles overlap each other?

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

    Suppose that you have defined the positions and sizes of the rectangles like this:

    enter image description here

    My C++ implementation is like this:

    class Vector2D
    {
        public:
            Vector2D(int x, int y) : x(x), y(y) {}
            ~Vector2D(){}
            int x, y;
    };
    
    bool DoRectanglesOverlap(   const Vector2D & Pos1,
                                const Vector2D & Size1,
                                const Vector2D & Pos2,
                                const Vector2D & Size2)
    {
        if ((Pos1.x < Pos2.x + Size2.x) &&
            (Pos1.y < Pos2.y + Size2.y) &&
            (Pos2.x < Pos1.x + Size1.x) &&
            (Pos2.y < Pos1.y + Size1.y))
        {
            return true;
        }
        return false;
    }
    

    An example function call according to the given figure above:

    DoRectanglesOverlap(Vector2D(3, 7),
                        Vector2D(8, 5),
                        Vector2D(6, 4),
                        Vector2D(9, 4));
    

    The comparisons inside the if block will look like below:

    if ((Pos1.x < Pos2.x + Size2.x) &&
        (Pos1.y < Pos2.y + Size2.y) &&
        (Pos2.x < Pos1.x + Size1.x) &&
        (Pos2.y < Pos1.y + Size1.y))
                     ↓  
    if ((   3   <    6   +   9    ) &&
        (   7   <    4   +   4    ) &&
        (   6   <    3   +   8    ) &&
        (   4   <    7   +   5    ))
    

提交回复
热议问题