Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pygame rect collision smaller than image

How can I define a rect collision detection smaller than image in pygame? I'd like to have a collision patter like the second image , but I'm having a cut image when a try to set the width and height in the method rect.

enter image description here

When I try to set using image size, I have the collision detection in red

    self.rect = pygame.rect.Rect(location, self.image.get_size())

If I set the size using width and height, I just have the third image

    self.rect = pygame.rect.Rect(location, (32, 150))

I really wouldn't like to use pixel perfect collision, because is the slowest collision detection, so someone have some idea how can I achieve the second image collision approach using Rect? Thanks.

like image 451
Wanderson Vieira Avatar asked Oct 19 '22 16:10

Wanderson Vieira


1 Answers

It seems that you are using pygames built in sprite module. (Please correct me if I am wrong)

You might know that each sprite consist of an image (which is drawn on a surface) and a rect object (sets location and size (!) of the image).

As Luke Taylor suggested, you could create a new rect object in your player class …

self.collideRect =  pygame.rect.Rect((0, 0), (32, 150))

… and set its location (according to your graphic) to

self.collideRect.midbottom = self.rect.midbottom

Every time you change the position of your player you must call this line too, so your self.collideRect rect object "moves" with your player on screen.

To test if a point (e.g. the mouse coordinates) is inside the self.collideRect, call

if self.collideRect.collidepoint(x, y) == True:
    print("You clicked on me!")
like image 200
elegent Avatar answered Nov 03 '22 04:11

elegent