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?
-
\$\begingroup\$ Technically, this has very little to do with pygame. It's more a generic algorithm. \$\endgroup\$Ikke– Ikke2011-09-02 10:26:49 +00:00Commented Sep 2, 2011 at 10:26
2 Answers
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.
-
\$\begingroup\$ MmHm, Okay, So Do I Have To Like, Assign Something To The Sprite ? \$\endgroup\$Firetryer– Firetryer2011-07-23 09:26:46 +00:00Commented Jul 23, 2011 at 9:26
-
2\$\begingroup\$ You call
is_a_collision = pygame.sprite.collide_mask(A, B), and if there was a collision, youis_a_collisionwill beTrue, if there wasn't a collision,is_a_collisionwill beFalse. Please remember to accept an answer if it helped you. \$\endgroup\$agf– agf2011-07-23 09:31:25 +00:00Commented Jul 23, 2011 at 9:31
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