How Can I Shoot a Bullet with the Space Bar?
In your code, the disappearance of the player when pressing the space bar is likely due to the separate loops for shooting and player movement. To fix this, incorporate both actions into the main application loop.
For bullet firing, utilize a list (e.g., bullet_list) to store bullet positions. When firing, add the starting position of the object firing the bullet to the list. Iterate through the bullet list, updating each bullet's position and removing any that leave the screen.
The while loop for the shoot method in your bullet class is not breaking despite the condition if y <= 0. This is because the condition is never met since y is increasing rather than decreasing. To fix this, change y -= self.speed to y = self.speed.
Additionally, implement event handling in your main application loop to capture key presses. Use pygame.key.get_pressed() to continuously get the state of keys. Based on the key press, update the position of the player and trigger bullet firing.
Here's a revised code snippet that incorporates these fixes:
<code class="python">bullets = [] while True: # Event handling for event in pygame.event.get(): pass if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: bullets.append(Bullet(p.x+p.width//2, p.y)) if event.key == pygame.K_LEFT: p.move_left() if event.key == pygame.K_RIGHT: p.move_right() # Update objects keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: p.move_left() if keys[pygame.K_RIGHT]: p.move_right() for b in bullets: b.update() if b.y <= 0: bullets.remove(b) # Clear display d.fill((98, 98, 98)) # Draw scene for b in bullets: b.draw() p.draw() # Update display win.update()</code>
The above is the detailed content of How to Fix Player Disappearance and Implement Bullet Shooting with Space Bar in Pygame?. For more information, please follow other related articles on the PHP Chinese website!