【问题标题】:Pygame Bullet Movement [duplicate]Pygame子弹运动[重复]
【发布时间】:2021-02-07 12:52:16
【问题描述】:

所以我试图编写一个太空入侵者游戏,但我在试图弄清楚如何射击子弹以使它们看起来像动画而不是传送到它们碰撞的最终位置(屏幕顶部)时卡住了,我没有不知道该怎么做我试图弄清楚很多但没有任何帮助它只是不断传送 笔记: player 是 Player 类的实例,所以我为什么要做'player'。我只是想练习类

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE:
        while player.bullet_rect.y > 0:
            player.bullet_rect.y -= bullet_velocity

【问题讨论】:

  • 这个问题是重复的。已经问了100次了,答案还是一样。

标签: python pygame bullet


【解决方案1】:

您必须在应用程序循环中实现子弹移动,而不是在事件循环内的附加循环中。添加一个fired 变量,指示按下 SPACE 是否会发射子弹。设置fired status 时移动项目符号。当子弹到达屏幕顶部时重置fired

fired = False

while run:
    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                fired = True

    if fired:
        player.bullet_rect.y -= bullet_velocity
        if player.bullet_rect.y < 0:
            fired = False

发射子弹的一般方法是将子弹的位置存储在一个列表中 (bullet_list)。发射子弹时,将子弹矩形的副本添加到列表中。起始位置是玩家的位置。使用for-loop 遍历列表中的所有项目符号。移动循环中每个子弹的位置。从离开屏幕的列表中删除一个项目符号 (bullet_list.remove(bullet_pos))。因此,必须运行列表的副本 (bullet_list[:])(请参阅 How to remove items from a list while iterating?)。使用另一个 for-loop 来blit 屏幕上剩余的子弹:

bullet_list = []

while run:
    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                
                # create bullet rectangle with the position of the player
                bullet_rect = 
                
                bullet_list.append(bullet_rect)

    for bullet_rect in bullet_list[:]:
        bullet_rect.y += bullet_velocity
        if bullet_rect.y < 0:
            bullet_list.remove(bullet_rect)

    # [...]

    for bullet_rect in bullet_list[:]
        # draw bullet at bullet_rect 
        # [...]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多