# C++ Get the overlapping rectangle of two possibly overlapping rectangles

## Recommended Posts

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?

##### Share on other sites

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.

##### Share on other sites

@ 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 */}

Edited by Fulcrum.013

##### Share on other sites
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

Edited by Aceticon

##### Share on other sites

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

##### Share on other sites

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;
}

## Create an account

Register a new account

1. 1
2. 2
Rutin
18
3. 3
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633701
• Total Posts
3013442
×