How do I detect collision between bullets and sprites in PyGame?
In PyGame, one can detect collisions using pygame.Rect objects. Rect objects include many methods for detecting collisions between two objects, even collisions between rectangular and circular objects.
Some examples:
pygame.Rect.collidepoint: Tests if a point is inside a rectangle.
pygame.Rect.colliderect : Tests if two rectangles overlap.
For collisions between pygame.sprite.Sprite and pygame.sprite.Group objects, one can use pygame.sprite.spritecollide(), pygame.sprite.groupcollide() or pygame.sprite.spritecollideany(). When using these methods, the collision detection algorithm can be specified by the collided argument:
The collided argument is a callback function used to calculate if two sprites are colliding.
Possible collided parameters are collide_rect, collide_rect_ratio, collide_circle, collide_circle_ratio, collide_mask.
Some examples:
pygame.sprite.spritecollide():
pygame.sprite.spritecollide() / collide_circle:
In your specific case, to detect a collision between a bullet and a sprite and delete both the sprite and the bullet, you can use pygame.sprite.spritecollide() and pygame.sprite.Group:
# [...] my_sprite = Sprite(sx, sy, name) my_bullet = Bullet(by, by) bullet_group = pygame.sprite.Group(my_bullet) sprite_group = pygame.sprite.Group(my_sprite) while True: # [...] collisions = pygame.sprite.spritecollide(my_bullet, sprite_group, True) for sprite in collisions: sprite_group.remove(sprite)
The above is the detailed content of How to Detect and Handle Bullet-Sprite Collisions in Pygame?. For more information, please follow other related articles on the PHP Chinese website!