如何在不改变面对每个循环的情况下改变射弹的位置?

时间:2014-05-17 22:59:48

标签: python pygame sprite

我已经编写了以下代码,在我看来它应该可以工作,但看起来“fireir”不断被设置为“面对”,而不仅仅是鼠标点击。使用此代码,当角色改变方向,或面对屏幕上的任何抛射物时,也会改变方向。 (这是在Python 3.3中)

我写这个的方式有什么问题? 有没有更好的方法来实现这一目标?

def update(char1, laser_list, facing, firedir):
 keys = pygame.key.get_pressed()
 if (keys[pygame.K_LEFT] or keys[pygame.K_a]): 
    char1.rect.x -= 2
    facing = "left"
 elif (keys[pygame.K_DOWN] or keys[pygame.K_s]): 
    char1.rect.y += 2
    facing = "down"
 elif (keys[pygame.K_UP] or keys[pygame.K_w]): 
    char1.rect.y -= 2
    facing = "up"
 elif (keys[pygame.K_RIGHT] or keys[pygame.K_d]): 
    char1.rect.x += 2
    facing = "right"

 if laser_list:
    #Move the laser
    if firedir == "up":
        laser.rect.y -= 4
    elif firedir == "down":
        laser.rect.y += 4
    elif firedir == "left":
        laser.rect.x -= 4
    elif firedir == "right":
        laser.rect.x += 4


 return(facing)

#main loop
done = False
while not done:
 for event in pygame.event.get():
    if event.type == pygame.QUIT:
        done = True

    if event.type == pygame.MOUSEBUTTONDOWN:
        if not laser_list:
            laser = Laser(facing)
            laser.rect.x = (char1.rect.x + 10)
            laser.rect.y = (char1.rect.y + 10)
            all_sprites_list.add(laser)
            laser_list.add(laser)

            firedir = facing


#update sprites
facing = update(char1, laser_list, facing, facing)  

1 个答案:

答案 0 :(得分:0)

这个问题是您将facing作为firedir传递,而您应该阅读传递给Laser构造函数的饰面。我不确定保存的位置(因为你没有显示Laser类定义),但我认为你想让update做类似的事情:

def update(char1, laser_list): # fewer parameters
    # key reading stuff, as before, which sets the local variable `facing`

    for laser in laser_list:       # loop over all lasers in the list
        if laser.firedir == "up":  # check an attribute of the laser for its direction
            laser.rect.y -= 4
        elif laser.firedir == "down":
            laser.rect.y += 4
        elif laser.firedir == "left":
            laser.rect.x -= 4
        elif laser.firedir == "right":
            laser.rect.x += 4

    return facing  # the returned facing will be used for lasers fired in the next frame!

另一种可能更容易的方法是在激光上存储velocity矢量而不是方向字符串。然后你可以使用相同的更新代码,无论激光的目标方向是什么(即使是对角线,如果你允许它们,也会起作用)。我不知道Laser设置代码是什么,但update逻辑将是:

 laser.rect.x += laser.velocity.x
 laser.rect.y += laser.velocity.y