Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 728
Maria Ines Parnisari Avatar asked Sep 03 '26 16:09

Maria Ines Parnisari


2 Answers

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

like image 151
Boris Strandjev Avatar answered Sep 05 '26 07:09

Boris Strandjev


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.

like image 39
argentage Avatar answered Sep 05 '26 06:09

argentage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!