Search code examples
pythonpygamecollision

Collision detection not working between the player and enemy


I am currently working on a top down shooter in which the player is in a fixed position with enemies coming in from random co-ordinates. However, the collision between the enemy colliding with the player is not working. I was wondering if anyone could help. (I'm not that good at coding). Any help is appreciated thanks.

code:

player class:

class Player(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = character
        self.rect = self.image.get_rect()
    def drawPlayer(self, image, angle, position):
        player=pygame.transform.rotate(image, angle)
        pRect=player.get_rect(center=position)
        screen.blit(player, pRect)

Enemy Class:

class Mob(pygame.sprite.Sprite):
    def __init__(self, start_x, start_y, dest_x, dest_y):
        
        pygame.sprite.Sprite.__init__(self)
        self.image = badguy

        self.rect = self.image.get_rect()

        self.rect.x = start_x
        self.rect.y = start_y

        self.floating_point_x = start_x
        self.floating_point_y = start_y

        x_diff = dest_x - start_x
        y_diff = dest_y - start_y
        angle = math.atan2(y_diff, x_diff);

        velocity = random.randrange(1,3)
        self.change_x = math.cos(angle) * velocity
        self.change_y = math.sin(angle) * velocity
        pygame.display.flip()

    def update(self):
        
        self.floating_point_y += self.change_y
        self.floating_point_x += self.change_x

        self.rect.y = int(self.floating_point_y)
        self.rect.x = int(self.floating_point_x)

collision part:

    all_sprites_list.update()

    hits = pygame.sprite.spritecollide(player, mobs, True)
    if hits:
        running = False

Solution

  • pygame.sprite.groupcollide() uses the .rect attributes of the pygame.sprite.Sprite objects to do the collision test. Hence you've to update the self.rect attribute, rather than using a the local variable pRect:

    class Player(pygame.sprite.Sprite):
        # [...]
    
        def drawPlayer(self, image, angle, position):
            player = pygame.transform.rotate(image, angle)
            self.rect = player.get_rect(center = position)
            screen.blit(player, self.rect)