Determine if two rectangles overlap each other?

前端 未结 23 1399
礼貌的吻别
礼貌的吻别 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 04:44

    Easiest way is

    /**
     * Check if two rectangles collide
     * x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
     * x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
     */
    boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2)
    {
      return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
    }
    

    first of all put it in to your mind that in computers the coordinates system is upside down. x-axis is same as in mathematics but y-axis increases downwards and decrease on going upward.. if rectangle are drawn from center. if x1 coordinates is greater than x2 plus its its half of widht. then it means going half they will touch each other. and in the same manner going downward + half of its height. it will collide..

提交回复
热议问题