Game Development Reference
In-Depth Information
18 - Collision Detection and Input
We don't want to repeat the code that checks all four corners for both rect1 and
rect2 , so instead we use a and b on lines 7 to 10. The for loop on line 5 uses the
multiple assignment trick so that on the first iteration, a is set to rect1 and b is set to
rect2 . On the second iteration through the loop, it is the opposite. a is set to rect2 and
b is set to rect1 .
We do this because then we only have to type the code for the if statement on line 7
once. This is good, because this is a very long if statement. The less code we have to type
for our program, the better.
13. return False
If we never return True from the previous if statements, then none of the eight corners
we checked are in the other rectangle. In that case, the rectangles did not collide and we
return False .
Determining if a Point is Inside a Rectangle
15. def isPointInsideRect(x, y, rect):
16. if (x > rect.left) and (x < rect.right) and (y >
rect.top) and (y < rect.bottom):
17. return True
The isPointInsideRect() function is used by the doRectsOverlap()
function. isPointInsideRect() will return True if the XY coordinates passed to it
as the first and second parameters are located "inside" the pygame.Rect object that is
passed as the third parameter. Otherwise, this function returns False .
Figure 18-3 is an example picture of a rectangle and several dots. The dots and the
corners of the rectangle are labeled with coordinates.
The pattern that points inside a rectangle have is an X-coordinate that is greater than the
X-coordinate of the left side and less than the X-coordinate of the right side, and a Y-
coordinate that is greater than the Y-coordinate of the top side and less than the Y-
coordinate of the bottom side. If any of those conditions are false, then the point is outside
the rectangle.
We combine all four of these conditions into the if statement's condition with and
operators because all four of the conditions must be True .
Search WWH ::




Custom Search