In the sprite demo, we left out the collision detection bit. Pygame has a number of useful collision detection functions in the Rect
class. For instance, we can check whether a point is in a rectangle or whether two rectangles overlap.
Beside the collision detection we will replace the mouse cursor with an image of a hammer that we created. It's not a very pretty image, but it beats the boring old cursor.
hit
method of the sprite demo code. In the new version, we check whether the mouse cursor is within the avatar sprite. Actually to make it easier to hit the head, we create a slightly bigger rectangle:def hit(self): mouse_x, mouse_y = pygame.mouse.get_pos() collided = False bigger_rect = self.rect.inflate(40, 40) if bigger_rect.collidepoint(mouse_x, mouse_y): collided = True if not self.degrees and collided: self.degrees = 1 self.original = self.image self.nhits += 1 else: self.nmisses += 1
pygame.mouse.set_visible(False)
A screenshot of the game is shown as follows:
The complete code for this example can be found in the code bundle of this book.
We learned a bit about collision detection, the mouse cursor, and rectangles in this recipe:
Function |
Description |
---|---|
|
This gets the mouse position as a tuple. |
|
This creates a bigger rectangle based on an offset. If the offset is negative this results in a smaller rectangle. |
|
This checks whether a point is within a rectangle. |
|
This hides the mouse cursor. |