碰撞检测在玩家和敌人之间不起作用

Collision detection not working between the player and enemy

我目前正在开发一款自上而下的射击游戏,其中玩家处于固定位置,敌人从随机坐标进入。但是,与玩家碰撞的敌人之间的碰撞不起作用。我想知道是否有人可以提供帮助。 (我不太擅长编码)。感谢任何帮助。

代码:

玩家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)

敌人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)

碰撞部分:

    all_sprites_list.update()

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

pygame.sprite.groupcollide() uses the .rect attributes of the pygame.sprite.Sprite 个对象做碰撞测试。因此,您必须更新 self.rect 属性,而不是使用局部变量 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)