Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Can someone tell me how to implement collision in Pygame?
For example I have a sprite called A and another one called B.
How do I detect if they collide in Pygame?

share|improve this question

migrated from stackoverflow.com Jul 23 '11 at 16:14

This question came from our site for professional and enthusiast programmers.

    
Technically, this has very little to do with pygame. It's more a generic algorithm. –  Ikke Sep 2 '11 at 10:26

2 Answers 2

up vote 4 down vote accepted

Take a look at:

http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect

And the several methods following it. You can test against a rectangle, circle, mask, sprite, or group of sprites.

You probably want

pygame.sprite.collide_mask(SpriteLeft, SpriteRight): return bool

Which checks if two sprites collide based on their bitmasks.

share|improve this answer
    
MmHm, Okay, So Do I Have To Like, Assign Something To The Sprite ? –  Firetryer Jul 23 '11 at 9:26
2  
You call is_a_collision = pygame.sprite.collide_mask(A, B), and if there was a collision, you is_a_collision will be True, if there wasn't a collision, is_a_collision will be False. Please remember to accept an answer if it helped you. –  agf Jul 23 '11 at 9:31
    
Awesome, Thanks For The Answer :) –  Firetryer Oct 8 '11 at 3:24

I use collisions based on rectangles. Both sprites need a .rect assigned to them.

Then check for a collision

  • pygame.sprite.collide_rect(A, B)

    (returns a boolean if there is a collision)

Alternatively you can use the rectangle to check for a collision, eg

  • A.rect.colliderect(B.rect)

    (returns a boolean if there is a collision)

I use rect collisions because they're faster than bitmap checks.

Pygame rect docs http://www.pygame.org/docs/ref/rect.html

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.