Firing Bullets towards the Cursor in PyGame
In PyGame, creating projectiles that follow the mouse cursor's direction can pose a challenge. Let's examine the provided code and address its shortcomings.
Existing Code Analysis
The current code aims to:
However, the implementation has some flaws:
Corrected Approach
To fix these issues, we adopt a different approach:
Initialize Bullet Parameters at Creation:
Pre-Rotate the Bullet:
Continuous Position Updating:
Example Implementation
<code class="python">import pygame import math # Bullet Class class Bullet: def __init__(self, x, y): # Calculate initial position and direction self.pos = (x, y) mx, my = pygame.mouse.get_pos() self.dir = (mx - x, my - y) # Normalize direction vector length = math.hypot(*self.dir) self.dir = (self.dir[0]/length, self.dir[1]/length) # Create bullet surface and rotate it self.bullet = pygame.Surface((7, 2)).convert_alpha() self.bullet.fill((255, 255, 255)) angle = math.degrees(math.atan2(-self.dir[1], self.dir[0])) self.bullet = pygame.transform.rotate(self.bullet, angle) self.speed = 2 # Adjust bullet speed as desired def update(self): # Update position based on scaled direction vector self.pos = (self.pos[0]+self.dir[0]*self.speed, self.pos[1]+self.dir[1]*self.speed) def draw(self, surface): # Draw bullet aligned with the correct direction bullet_rect = self.bullet.get_rect(center=self.pos) surface.blit(self.bullet, bullet_rect) # PyGame Main Loop pygame.init() window = pygame.display.set_mode((500, 500)) clock = pygame.time.Clock() bullets = [] # List to store bullet objects while True: clock.tick(60) # Set desired frame rate for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: # Create a new bullet and add it to the list bullets.append(Bullet(*pygame.mouse.get_pos())) # Update and draw bullets for bullet in bullets[:]: bullet.update() if not window.get_rect().collidepoint(bullet.pos): # Remove bullets that leave the window boundary bullets.remove(bullet) else: # Draw bullet at its current position bullet.draw(window) # Render the updated display pygame.display.update()</code>
The above is the detailed content of How to Make Bullets Follow the Mouse Cursor in PyGame?. For more information, please follow other related articles on the PHP Chinese website!