发射多个子弹并按一下键即可更改其位置

时间:2019-05-06 09:04:47

标签: python pygame

我正在为自己的娱乐目的而创建SHMUP类型的游戏,但我在每次按下键时如何将“子弹生成器”位置更改为另一个固定位置时都遇到了麻烦,比如说我想要一个进攻性的游戏风格,一个防守球员,我希望在视觉上有所不同,并决定与玩家保持子弹距离,但我不知道如何,愿意帮助我吗?

当前情况:

class MainFire(pygame.sprite.Sprite):
    def __init__(self, x, y, filename, posx, posy):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_folder, filename)).convert()
        self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.bottom = y
        self.speedy = - 20
        posx += self.rect.centerx
        posy += self.rect.bottom

    def update(self):
        self.rect.y += self.speedy
        if self.rect.bottom < 0:
            self.kill()

class SubFire(pygame.sprite.Sprite):
    def __init__(self, x, y, filename, posx, posy):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_folder, filename)).convert()
        self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.bottom = y
        self.speedy = - 20
        posx += self.rect.centerx
        posy += self.rect.bottom

    def update(self):
        self.rect.y += self.speedy
        if self.rect.bottom < 0:
            self.kill()
        elif self.rect.left < -10:
            self.kill()
        elif self.rect.right > GAMEWIDTH:
            self.kill()

我认为,如果我修复posx和posy最终将起作用,则posx应该将x和整型与y一起添加为posy(将子弹赋予新位置,速度已经确定,问题是“枪出现而不是子弹本身”)

1 个答案:

答案 0 :(得分:1)

好吧,首先要针对不同的发射角度摆脱这些单独的类。一旦知道了不同镜头的所有内容(起始位置,速度,图像)可能不同,我们就可以为所有这些镜头创建1类,并将这些参数传递给init()函数。我已经将它的所有Main_fire和sub_fire类都删除了,称为Bullet(),这应该更易于使用。

def fire(self):
    #this is lv2 and the base needs to be changed, it gains the subfire then another subfire set
    mfl = Bullet(self.rect.centerx, self.rect.top, "Alessa_MF.png",-20,0)
    all_sprites.add(mfl)
    bullets.add(mfl)
    sfl = Bullet(self.rect.centerx, self.rect.top, "Alessa_SF.png",-15,2)
    all_sprites.add(sfl)
    bullets.add(sfl)
    mfr = Bullet(self.rect.centerx, self.rect.top,"Alessa_SF.png",-15,-2)
    all_sprites.add(mfr)
    bullets.add(mfr)
    sfr = Bullet(self.rect.centerx, self.rect.top,"Alessa_SF.png",-10,-2)
    all_sprites.add(sfr)
    bullets.add(sfr)
    #fire_sound.play()

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y,filename,vx,vy):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_folder, filename)).convert()
        self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()
        self.rect.bottom = y
        self.rect.centerx = x-25
        self.speedy = vy
        self.speedx = vx

    def update(self):
        self.rect.y += self.vy
        self.rect.x += self.vx
        if self.rect.bottom < 0:
            self.kill()