Home  >  Article  >  Backend Development  >  How to Make Bullets Shoot Towards the Mouse Cursor in PyGame?

How to Make Bullets Shoot Towards the Mouse Cursor in PyGame?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 08:49:02275browse

How to Make Bullets Shoot Towards the Mouse Cursor in PyGame?

How to shoot a bullet towards the mouse cursor in PyGame?

You're encountering issues in making your bullet shoot towards the mouse cursor in PyGame. Your code currently involves creating a Bullet class, adding bullets, and calculating the angle. However, you're finding that the bullets are not rotating and moving as expected. Let's go over the approach and improve it.

Firstly, the issue with rotation stems from the fact that pygame.transform.rotate creates a new rotated surface without updating your existing bullet object. To rotate a sprite in place, you need to use sprite.image = pygame.transform.rotate(sprite.image, angle).

As for getting the direction, you're using a constantly changing angle between the player and the mouse position, which results in inconsistent bullet movement. Instead, the direction needs to be set once when the bullet is fired:

self.dir = pygame.mouse.get_rel()  # Relative movement since the last event

To normalize the direction and set the speed, you can do this:

dist = math.sqrt(self.dir[0]**2 + self.dir[1]**2)
self.speed = self.speed / dist
self.dir = (self.dir[0]/dist, self.dir[1]/dist)

Finally, you need to add the calculated speed to the bullet's position in the update function:

self.pos += self.speed[0], self.speed[1]

Here's an example that incorporates the mentioned improvements:

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10, 10))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect()
        self.speed = 10

    def update(self):
        angle = math.atan2(self.dir[1], self.dir[0])
        self.image = pygame.transform.rotate(self.image, -angle * (180 / math.pi))
        self.pos += self.speed[0], self.speed[1]
        self.rect = self.image.get_rect(center=self.pos)

The above is the detailed content of How to Make Bullets Shoot Towards the Mouse Cursor in PyGame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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