如果我在短短的几秒钟内发射了第二枚子弹,我试图解决触发的子弹消失的原因。我想screen.fill(GRAY)
可能是原因,应该在Class Bullet()
内部,或者我需要在其他地方使用all_sprites_list.update()
。
这是我的MWE代码:
import pygame
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (128,128,128)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class Cowboy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([14,20])
self.image.fill(BLUE)
self.rect = self.image.get_rect()
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("bullet.png").convert()
self.rect = self.image.get_rect()
def update(self):
self.rect.y += -3
def main():
pygame.init()
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size, pygame.RESIZABLE)
all_sprites_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
enemies_list = pygame.sprite.Group()
bullet = Bullet()
enemy = Cowboy()
enemies_list.add(enemy)
all_sprites_list.add(enemy)
enemy.rect.y = 50
enemy.rect.x = 50
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
bullet_list.add(bullet)
all_sprites_list.add(bullet)
bullet.rect.x = 340
bullet.rect.y = 200
screen.fill(GRAY)
all_sprites_list.draw(screen)
clock.tick(60)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
最佳答案
当按下鼠标按钮时,您必须创建一个Bullet
的新实例,并且必须调用在update
上调用update
的项目符号的bullet_list
方法:
def main():
# [...]
# bullet = Bullet() <--- DELETE
# [...]
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# create new bullet and add it to the groups
bullet = Bullet()
bullet.rect.center = enemy.rect.center
bullet_list.add(bullet)
all_sprites_list.add(bullet)
# update the bullets
bullet_list.update()
# [...]
关于python - 拍摄的第一张照片与第二张照片重叠,或者在第二张照片等之后消失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60212097/