皮加梅子弹运动

2024-04-30 01:58:51 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着编写一个太空入侵者游戏,我在尝试如何射击子弹时被卡住了,所以子弹看起来像动画,而不是传送到它们碰撞的末端位置(屏幕顶部),我不知道该怎么做,我试着弄明白很多,但没有任何帮助,只是继续传送 注: 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

Tags: 实例rectevent游戏if屏幕type动画
1条回答
网友
1楼 · 发布于 2024-04-30 01:58:51

必须在应用程序循环中实现项目符号移动,而不是在事件循环中的附加循环中。添加一个fired变量,该变量指示按空格键是否触发子弹。设置fired 状态时移动项目符号。当项目符号到达屏幕顶部时重置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 
        # [...]

相关问题 更多 >