区分碰撞中的精灵

问题描述 投票:1回答:3

我正在创建一个类似于经典“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
3个回答
0
投票

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]

我不知道精灵中有什么,但我想你可以指定一个字段来跟踪它是什么类型。或者如果有精灵子类型​​(我再也不知道pygame或你正在使用的任何东西),你可以使用isinstance。

if isinstance(sprite, type)

关于pygame和overlap_sprites的另一个问题是:Object not behaving correctly


0
投票

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


-1
投票

只需使用type()

EG

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()
© www.soinside.com 2019 - 2024. All rights reserved.