Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17466

Rectangular collision detection

class Rectangle{
public:
   float x, y, width, height;
   // (x,y) is the lower left corner of the rectangle
};

Is this algorithm correct?

bool Rectangle::colidesWith(Rectangle other) {
   if (x+width < other.x) return false; // "other" is on the far right
   if (other.x+other.width < x) return false; //"other" is on the far left
   if (y+height < other.y) return false // "other" is up
   if (other.y+other.height < y) return false // "other" is down
   return true;
}

Upvotes: 3

Views: 1907

Answers (3)

Alexander Chertov
Alexander Chertov

Reputation: 2108

To me, a more intuitive way of writing this condition is:

( max(r1.x, r2.x) < min(r1.x+r1.w, r2.x+r2.w) ) &&
( max(r1.y, r2.y) < min(r1.y+r1.h, r2.y+r2.h) )

And actually this can be generalized to any dimensionality.

Upvotes: 0

argentage
argentage

Reputation: 2778

Yep. You can view it as a special case of the hyperplane separation theorem which is the general version of this problem. You are projecting these rectangles onto the X and Y axis and then checking that the resulting line segments have some separation between them.

Upvotes: 4

Boris Strandjev
Boris Strandjev

Reputation: 46943

It is if the rectangles are filled (i.e. you count as collision the case in which one of them is inside the other).

Upvotes: 5

Related Questions