Detecting collisions (Intermediate)

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.

How to do it...

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.

  1. Updating the hit method: We will update the 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

  2. Replacing the mouse cursor: All the steps necessary to replace the mouse cursor were already covered. Except making the mouse cursor invisible:
    pygame.mouse.set_visible(False)

    A screenshot of the game is shown as follows:

    How to do it...

The complete code for this example can be found in the code bundle of this book.

How it works...

We learned a bit about collision detection, the mouse cursor, and rectangles in this recipe:

Function

Description

pygame.mouse.get_pos()

This gets the mouse position as a tuple.

self.rect.inflate(40, 40)

This creates a bigger rectangle based on an offset. If the offset is negative this results in a smaller rectangle.

bigger_rect.collidepoint(mouse_x, mouse_y)

This checks whether a point is within a rectangle.

pygame.mouse.set_visible(False)

This hides the mouse cursor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset