Home > Backend Development > Python Tutorial > How to Make Bullets Follow the Mouse Cursor in PyGame?

How to Make Bullets Follow the Mouse Cursor in PyGame?

Barbara Streisand
Release: 2024-11-03 18:53:29
Original
886 people have browsed it

How to Make Bullets Follow the Mouse Cursor in PyGame?

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:

  • Create a Bullet class to represent projectiles.
  • Initialize a Game class to handle bullet generation and movement.

However, the implementation has some flaws:

  • It uses pygame.transform.rotate incorrectly, which returns a new rotated surface instead of transforming the original object.
  • It attempts to calculate the movement direction and rotation angle dynamically, which leads to unpredictable bullet behavior.

Corrected Approach

To fix these issues, we adopt a different approach:

  1. Initialize Bullet Parameters at Creation:

    • When creating a new bullet, calculate its starting position and direction vector towards the mouse cursor.
    • Normalize the direction vector to create a unit vector.
  2. Pre-Rotate the Bullet:

    • Rotate the bullet surface to align with the calculated direction vector.
  3. Continuous Position Updating:

    • Update the bullet's position by incrementally adding the scaled direction vector to its current position.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template