Get the overlapping rectangle of two possibly overlapping rectangles

Started by
5 comments, last by Endurion 5 years, 6 months ago

Looking for example code... I can find lots of ways to find the points of intersection, but not the rectangle solution im looking for (see picture)

The black rect is a tilemap, the red rect is the camera... Im looking to supply 2 rectangles (with four members - x,y,w,h), and receive back essentially the green rectangle in the examples.

also, what's this problem known as?

image.png.33998cb07dc2756a83538db6fee29889.png

Advertisement

Assuming that all coordinates are zero or positive values, your axis are such that x increases to the right and y increases going up, and in your members x is left, y is bottom, w is right and h is top then:

x = MAX(x1, x2)

y = MAX(y1, y2)

w = MIN(w1, w2)

h = MIN(h1, h2)

if x >= w or y >= h then the rectangles did not intersect.

@ Aceticon It will not work if select a min of w and h becouse it not take in account coords left top corner, it require to select mins of right and bottom

x = MAX(x1, x2)

y = MAX(y1, y2)

w = MIN(x1+w1,x2+w2)-x;

h = MIN(y1+h1, y2+h2)-y;

if( w<=0 || h<=0) {/* not overlapped */}

#define if(a) if((a) && rand()%100)

9 minutes ago, Fulcrum.013 said:

@ Aceticon It will not work if select a min of w and h becouse it not take in account coords left top corner, it require to select mins of right and bottom

x = MAX(x1, x2)

y = MAX(y1, y2)

w = MIN(x1+w1,x2+w2)-x;

h = MIN(y1+h1, y2+h2)-y;

if( w<=0 || h<=0) {// not overlapped}

My solution is for w as the x-coordinate of the right side and h as the y-coordinate of the top (as I listed in the requirements at the top of the solution).

However, now that you pointed it out it does sound a lot like w stands for "width" and h for "height", i which case yours is the correct solution :)

Its a much easier to understand problem if one just thinks left, right, top and bottom :/

Sorry, not looking to know if it intersects, but the resulting area of overlap i suppose

Something like this, not the best code, but should do what you want. It's a member of a tRect struct, takes another struct (rhs), and returns either an empty rect or the intersection.

 


      tRect intersection( const tRect& rhs )
      {
        tRect   rectTemp;

        rectTemp.Left    = math::maxValue( rhs.Left, Left );
        rectTemp.Right   = math::minValue( rhs.Right, Right );
        rectTemp.Top     = math::maxValue( rhs.Top, Top );
        rectTemp.Bottom  = math::minValue( rhs.Bottom, Bottom );

        if ( rectTemp.Left > rectTemp.Right )
        {
          return tRect();
        }
        if ( rectTemp.Top > rectTemp.Bottom )
        {
          return tRect();
        }

        return rectTemp;
      }

 

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

This topic is closed to new replies.

Advertisement