我将如何处理相同类型多个精灵的碰撞检测检查



我正在尝试处理多个精灵的碰撞检查,以对玩家角色进行检查。这是相关的代码,Enemy类创建了一个应该由图像表示的新精灵,并且Character类相似,除了它是玩家可以控制的精灵。这是我从项目中删除的相关代码。

    self.all_sprites_list = pygame.sprite.Group()
    sprite = Character(warrior, (500, 500), (66, 66))
    enemies = []
    for i in range(10):
        enemy = Enemy("evilwizard")
        enemies.append(enemy)
        self.all_sprites_list.add(enemy)
    self.all_sprites_list.add(sprite)
class Enemy(pygame.sprite.Sprite):
# This class represents the types of an enemy possible to be rendered to the scene
def __init__(self, enemy_type):
    super().__init__()  # Call sprite constructor
    # Pass in the type of enemy, x/y pos, and width/height (64x64)
    self.image = pygame.Surface([76, 76])
    self.image.fill(WHITE)
    self.image.set_colorkey(WHITE)
    self.rect = self.image.get_rect()
    self.rect.x = random.randrange(10, 1150)  # random start
    self.rect.y = random.randrange(10, 590)   # random start
    self.speed = 2
    self.move = [None, None]  # x-y coordinates to move to
    self.image = pygame.image.load(FILE_PATH_ENEMY + enemy_type + ".png").convert_alpha()
    self.direction = None  # direction to move the sprite`
class Character(pygame.sprite.Sprite):
    def __init__(self, role, position, dimensions):
    """
    :param role: role instance giving character attributes
    :param position: (x, y) position on screen
    :param dimensions: dimensions of the sprite for creating image
    """
    super().__init__()
    # Call the sprite constructor
    # Pass in the type of the character, and its x and y position, width and height.
    # Set the background color and set it to be transparent.
    self.image = pygame.Surface(dimensions)
    self.image.fill(WHITE)
    self.image.set_colorkey(WHITE)
    self.image = pygame.image.load(FILE_PATH_CHAR + role.title + ".png").convert_alpha()
    # Draw the character itself
    # position is the tuple (x, y)
    self.rect = self.image.get_rect()
    self.rect.x, self.rect.y = position
    self.attack = role.attack
    self.health = role.health
    self.title = role.title

pygame具有pygame.sprite.spritecollide,以检查pygame.sprite.Sprite()pygame.sprite.Group()

之间的碰撞

它还具有检查碰撞的其他功能 - 请参阅DOC有关Sprite

最新更新