1

I have the following code:

def collideRect(r1,r2,r3,r4):
    """Tests for collisions between two rectangles"""
    if r1[0]<r4[0] and r2[0]>r3[0] and r1[1]<r4[1] and r2[1]>r3[1]:
        return True
    return False

which is a simple test to see if two rectangular areas intersect (where r1 and r2 are the two coordinates defining the rectangle, i.e. the opposite corners, and r3 and r4 representing the second rectangle).

There is a very simple loophole in the equation though, and it is the fact that if one rectangle is defined by the top-left and bottom-right coordinates, and the second rectangle by its top-right and bottom-left coordinates, the test will be inaccurate.

Take the following example:

>>>r1, r2 = (0, 0), (10, 10)
>>>r3, r4 = (0, 10), (10, 0)

>>>collideRect(r1 ,r2 ,r3, r4)
False

For the application in which I'm using this function I need it to be versatile enough to be able to accurately calculate rectangular intersections without having to define the same corners for both rectangles.

What would be a simple fix to this problem?

1
  • 1
    Turns out collision detection is a non-trivial problem. Not to mention that defining opposite corners means you can have rotated and invalid rectangles. Commented Jan 3, 2014 at 1:24

1 Answer 1

4

You can ensure you have the bottom left and top right corners by using the following function:

def standardize(p1, p2):
    xs, ys = zip(p1, p2)
    return (max(xs), max(ys)), (min(xs), min(ys))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that works perfectly! I realize the question is quite simple, and I probably should've just worked it out on my own, but thanks anyways for helping me out!

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.