Creating Collision In Pygame
Solution 1:
I've created two sprite groups: all_sprites
which contains all sprites and is used to update and draw them with just two lines of code, and the bananas
group which is used to check for collisions between the macaco and the bananas. Then we need the pygame.sprite.spritecollide
function to get the collided sprites. You have to pass a sprite instance and a sprite group and it'll check for you if the sprite has collided with the sprites in the group. It returns the collided bananas as a list over which you can iterate to do something with them or for example to increment a points counter.
You have to call the __init__
method of the parent class in your sprites to be able to use them correctly with sprite groups (do that with the super
function super().__init__()
(in Python 2 super(Macaco, self).__init__()
).
To update the positions of your sprites, set their topleft
(or center
) attribute to the new x, y coordinates.
To get a rect from an image call self.rect = self.image.get_rect()
.
import sys
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
classMacaco(pygame.sprite.Sprite):
def__init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill((190, 140, 20))
self.rect = self.image.get_rect()
self.x = 300
self.y = 640
self.speed = 20defkeyboard(self, keys):
if keys[pygame.K_RIGHT]:
self.x += self.speed
elif keys[pygame.K_LEFT]:
self.x -= self.speed
defupdate(self):
self.rect.topleft = self.x, self.y
classBanana(pygame.sprite.Sprite):
def__init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill((230, 230, 40))
self.rect = self.image.get_rect()
self.x = random.randrange(0, 770)
self.y = -50
self.speed = 5defupdate(self):
self.y += self.speed
self.rect.topleft = self.x, self.y
macaco = Macaco()
banana = Banana()
all_sprites = pygame.sprite.Group(macaco, banana)
bananas = pygame.sprite.Group(banana)
clock = pygame.time.Clock()
running = Truewhile running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = Falseelif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
keys = pygame.key.get_pressed()
macaco.keyboard(keys)
all_sprites.update()
# Collision detection. Check if macaco collided with bananas group,# return collided bananas as a list. dokill argument is True, so# that collided bananas will be deleted.
collided_bananas = pygame.sprite.spritecollide(macaco, bananas, True)
for collided_banana in collided_bananas:
print('Collision.')
screen.fill((70, 40, 70))
all_sprites.draw(screen)
pygame.display.update()
clock.tick(30)
pygame.quit()
sys.exit()
Post a Comment for "Creating Collision In Pygame"