Skip to main content
gamedev.net
🔒 Locked

Overlapping rectangles

Started by jamescox3k 5 replies 200+ views
Original Post
jamescox3k
jamescox3k
I carn''t rember how this works, say I have 2 rectangles defined like this struct Rect { int x, y, w, h; }; How could i find out if 2 rectngles overlap I''ve got it working with lots of for-loop but shurly theres a mathmatical way of doing it?
JC
ga
ga
generally:
for every dimension, look if
(lower1 < upper2) AND (upper1 > lower2)

if this condition is satisfied in every dimension, the two axis-aligned volumes (areas, ...) overlap..
for your case the condition is


rect1.x < rect2.x + rect2.w && rect1.x + rect1.w > rect2.x &&
rect1.y < rect2.y + rect2.h && rect1.y + rect1.h > rect2.y


GA
Visit our homepage: www.rarebyte.de.stGA
theNestruo
theNestruo

  
bool areOverlapping (Rect a, Rect b) {
return ((((a.x >b.x) && (a.x <b.x+b.w)) ||
((a.x+w>b.x) && (a.x+w<b.x+b.w))) &&
(((a.y >b.y) && (a.y <b.y+b.h)) ||
((a.y+h>b.y) && (a.y+h<b.y+b.h))))
}


Try this. I''m not sure it works (I''ve not tested it). Maybe there are better ways to do it.

theNestruo

Syntax error in 2410
Ok
theNestruoSyntax error in 2410Ok
ga
ga
theNestruo: your method won''t work correctly...
it returns false if either x or y interval of rectangle b is completely in the according interval of rectangle a...
e.g. if a.x = 0, a.w = 3, b.x = 1, b.w = 1



GA
Visit our homepage: www.rarebyte.de.stGA
Arion
Arion
I use this algo for rectangle collision:


    
short int Rect_Rect_Collide ( Rect rect_1, Rect rect_2 )
{
// Quick Reject Stuff

if ( rect_1.h < rect_2.y ) return(0);
if ( rect_1.y > rect_2.h ) return(0);
if ( rect_1.w < rect_2.x ) return(0);
if ( rect_1.x > rect_2.w ) return(0);

return(1);
}// end Rect_Rect_Collide



[EDIT] Translated to your Rect structure. [/EDIT]

Guy

[edited by - Arion on December 19, 2002 3:37:12 PM]
ga
ga
Arion: you should write rect.x + rect.w instead of rect.w and rect.y + rect.h instead of rect.h, h and w are width and height i suppose

GA
Visit our homepage: www.rarebyte.de.stGA
Arion
Arion
quote:
Original post by ga
Arion: you should write rect.x + rect.w instead of rect.w and rect.y + rect.h instead of rect.h, h and w are width and height i suppose

GA


Yea, I'm a little confused about the structure.Maybe I can re-write it.

Let's see:

      

short int Rect_Rect_Collide ( Rect rect_1, Rect rect_2 ){

// Quick Reject Stuff


if ( ( rect_1. y + rect_1.h ) < rect_2.y ) return(0);
if ( rect_1.y > ( rect_2.y + rect_2.h ) ) return(0);
if ( ( rect_1.x + rect_1.w ) < rect_2.x ) return(0);
if ( rect_1.x > ( rect_2.x + rect_2.w ) ) return(0);

return(1);

}// end Rect_Rect_Collide




Guy


[edited by - Arion on December 19, 2002 4:46:03 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.