【问题标题】:Differentiating between sprites in collision区分碰撞中的精灵
【发布时间】:2014-05-25 22:00:48
【问题描述】:

我正在创建一个类似于经典“astrocrash”游戏的程序,但有多种类型的弹药,每种只影响特定类型的目标。 self.overlapping_sprites() 方法将识别任何重叠的精灵并采取相应的行动,但我如何让程序检测重叠的精灵是否属于特定类型?

class Krabbypatty(games.Sprite):
LETTUCE = 1
TOMATO = 2
PATTY = 3
images = {LETTUCE : games.load_image("tamatoandpatty.bmp"),
                 TOMATO : games.load_image("lettuceandpatty.bmp"),
                 PATTY : games.load_image("lettuceandtomato.bmp") }
SPEED = 3
def __init__(self, x, y, krabbypattytype):
    super(Krabbypatty, self).__init__(
        image = Krabbypatty.images[krabbypattytype],
        x=x, y=y,
        dx = random.choice([1, -1]) * Krabbypatty.SPEED * random.random()/krabbypattytype,
        dy = random.choice([1, -1]) * Krabbypatty.SPEED * random.random()/krabbypattytype)
    self.krabbypattytype = krabbypattytype
def update(self):
    if self.top > games.screen.height:
        self.bottom = 0
    if self.bottom < 0:
        self.top = games.screen.height
    if self.left > games.screen.width:
        self.right = 0
    if self.right < 0:
        self.left = games.screen.width
    if self.overlapping_sprites:
        sprite.change_patty()
def change_patty(self):

【问题讨论】:

    标签: python pygame collision-detection collision sprite


    【解决方案1】:

    self.overlapping_sprints 是一个精灵列表,对吧?

    尝试迭代 self.overlapping_sprites

    for sprite in self.overlapping_sprites:
       sprite.dosomething()
    

    或者

    sprites = [sprite for sprite in self.overlapping_sprites if sprite.whatever == 1]
    

    我不知道精灵中有什么,但我假设您可以分配一个字段来跟踪它是什么类型。 或者,如果有 sprite 子类型(同样我不知道 pygame 或您使用的任何东西),您可以使用 isinstance。

    if isinstance(sprite, type)
    

    关于 pygame 和overlay_sprites 的另一个 SO 答案在这里:Object not behaving correctly

    【讨论】:

      【解决方案2】:

      最“Pygame”的解决方案是使用pygame.sprite.Group 来存储精灵并使用pygame.sprite.groupcollide 来检测某些类型的精灵是否发生碰撞。所以你可以为敌人创建enemy_type_a 组,为可能伤害这类敌人的射弹创建type_a_destroyers 组。

      【讨论】:

        【解决方案3】:

        只需使用type()

        例如

        def update(self):
            for touch in self.overlapping_sprites:
                if type(touch) is wall:
                    print("Hit a wall")
                    self.horizontal_bounce()
                elif type(touch) is roof:
                    print("you hit the roof")
                    self.vertical_bounce()
                elif type(touch) is block:
                    self.vertical_bounce()
                self.score.increase_score(10)
        
            if self.bottom>games.screen.height:
                self.block.end_game()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-14
          • 1970-01-01
          相关资源
          最近更新 更多