3
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;
}
1
  • Is +ve Y up? If so, it looks ok. Commented Dec 17, 2012 at 17:51

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

You mean that if they aren't filled and one of them is inside the other then my algorithm won't work? Will it work in all the other cases?
As far as I can tell, yes. Also, yes for the first question.
@l19 - Your rectangles ARE filled. If one of your rectangles is inside another one then that will be counted as a collision. IF that was what you wanted then all is good. You only need to change something if that behaviour is not what you wanted.
4

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.