0

so I was programming again this morning and I wanted to write that the player in my small game can shoot bullets. That worked fine but theres an issue: I wrote for the x and the y coordinates of the 'bullet spawner' player.x and player.y and I thought that the bullets would shoot from the player's position. but they don't. They shoot from the position, where the player was in the beginning of the game and the spawner doesn't move. So I tried to do this with a while loop and the bool isMoving, that only is True if the player moves:

...
isMoving = False
...
bullets = []
position = (player.x, player.y)
while isMoving:
   position = (player.x, player.y)
...
if keys[pygame.K_d] or keys[pygame.K_a] or keys[pygame.K_w] or keys[pygame.K_s] or keys[pygame.K_UP] or keys[pygame.K_DOWN] or keys[pygame.K_LEFT] or keys[pygame.K_RIGHT]:
    isMoving = True
else:
    isMoving = False

But if I run pygame now, the window just freezes. If I remove the while loop again, it works but it shoots from the player's first position again. Oh, and I get the error " while isMoving: UnboundLocalError: local variable 'isMoving' referenced before assignment " Any ideas how to fix that?

  • And yes, I defined the bullets and everything before – PhoenixAnton Oct 23 '21 at 09:15
  • I guess this code is in the application loop. Why do you need a loop in the application loop? – Rabbid76 Oct 23 '21 at 09:22
  • @Rabbid76 How can I do it else? – PhoenixAnton Oct 23 '21 at 09:24
  • You need to create a new bullet object when it is shot at the player's position. See [How can i shoot a bullet with space bar?](https://stackoverflow.com/questions/59687250/how-can-i-shoot-a-bullet-with-space-bar/59689297#59689297) and [How do I stop more than 1 bullet firing at once?](https://stackoverflow.com/questions/60122492/how-do-i-stop-more-than-1-bullet-firing-at-once/60125448#60125448). – Rabbid76 Oct 23 '21 at 09:24

1 Answers1

0

Pygame should run in a main while loop which has all the main actions inside it. Try setting the position at the start, then inside the while loop check for pygame events that trigger the isMoving change. Nested while loops will cause issues with pygame. Use if functions inside the while loop instead of another while loop. For example,

position = (player.x, player.y) # initial position
while isRunning:
    isMoving = False
    # PyGame event interaction
    for event in pygame.event.get():
        # Exits loop
        if event.type == pygame.QUIT:
            isRunning = False
        # Check if key is pressed
        if event.type == pygame.KEYDOWN:
            keys = [pygame.K_a, pygame.K_w, pygame.K_s, pygame.K_d, pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]
            if event.key in keys:
                isMoving = True
        
    if isMoving:
        position = (player.x, player.y)
        # do other stuff