简体   繁体   中英

Pygame collision detect with PNG and rect?

I did recently ask this question, however I only got one answer and it didn't really explain enough for me. I need to check for a collision between two objects. One is a PNG image loaded in the following way:

 bird = pygame.image.load("bird.png").convert_alpha()

Another is a pygame rectangle created and drawn in the following way:

pipeTop = pygame.draw.rect(screen, (0,200,30), Rect((scrollx,0),(30,height)))

I have been told that the best way to do this is by making my bird a sprite in class Spirte: This doesn't really help me as I can find absolutly no tutorials on creating/ converting an image to a sprite. I would also not really no what methods I would need, though I probably assume I only need __init_ (I missed the second underscore due to formatting) and in the init method I do not know what I would put. Thank you for any help you can give; however unfortunatly I am very new to both Pygame and OOP so any extra detail and/or explanations are greatly appreciated.

EDIT: I currently have tried this:

 if bird.colliderect(pipeTop):

but it just raises the following error:

 AttributeError: 'pygame.Surface' object has no attribute 'colliderect'

You can use pygame.Surface.get_rect() to get a rectangle for collision, however, note the docs:

This rectangle will always start at 0, 0 with a width. and height the same size as the image.

You will probably want to change it's position to where you are choosing to draw the image to screen.

In general, you probably want to look into using sprites to make this process easier. Sprites manage both the image and the position in a single object, making it easier to do tasks like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM