Game Development Reference
In-Depth Information
Figure 18-2: Examples of intersecting rectangles (on the left) and rectangles that do not intersect (on the right).
We will make a single function that is passed two pygame.Rect objects. The function,
doRectsOverlap() , will return True if they do and False if they don't.
There is a very simple rule we can follow to determine if rectangles intersect (that is,
collide). Look at each of the four corners on both rectangles. If at least one of these eight
corners is inside the other rectangle, then we know that the two rectangles have collided.
We will use this fact to determine if doRectsOverlap() returns True or False .
5. for a, b in [(rect1, rect2), (rect2, rect1)]:
6. # Check if a's corners are inside b
7. if ((isPointInsideRect(a.left, a.top, b)) or
8. (isPointInsideRect(a.left, a.bottom, b)) or
9. (isPointInsideRect(a.right, a.top, b)) or
10. (isPointInsideRect(a.right, a.bottom, b))):
11. return True
Above is the code that checks if one rectangle's corners are inside another. Later we will
create a function called isPointInsideRect() that returns True if the XY
coordinates of the point are inside the rectangle. We call this function for each of the eight
corners, and if any of these calls return True , the or operators will make the entire
condition True .
The parameters for doRectsOverlap() are rect1 and rect2 . We first want to
check if rect1 's corners are inside rect2 and then check if rect2 's corners are in
rect1 .
Search WWH ::




Custom Search