Prabhu Raja

Tuesday, July 24, 2007

Detect overlapping objects

Detect overlapping objects or rectangles

How to detect overlapping rectangle objects

Assume that we have two rectangles naming rect1 and rect2

Both has properties like x, y, width and height, so here

We can create additional properties like x2 and y2 to simplify the task like this:

rect1.x1 = rect1.x;
rect1.y1 = rect1.y;
rect1.x2 = (rect1.x+rect1.width);
rect1.y2 = (rect1.y+rect1.height);

if(rect1.y2 >= rect2.y1 && rect1.y1 <= rect2.y2 && rect1.x2 >= rect2.x1 && rect1.x1 <= rect2.x2) {
alert(“rect1 and rect2 are overlapping”);
}

Hope this helps