Home  >  Article  >  Backend Development  >  Why Are My Pygame Bullets Not Moving Towards the Mouse?

Why Are My Pygame Bullets Not Moving Towards the Mouse?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 04:48:30233browse

Why Are My Pygame Bullets Not Moving Towards the Mouse?

Bullet Trajectory in Pygame: A Troubleshooting Guide

This discussion aims to address a common issue encountered when firing bullets toward the mouse position in Pygame: the bullets either don't move or exhibit erratic behavior.

Understanding the Problem

At the time of firing, the bullet's position and the direction vector toward the mouse need to be determined. However, the code provided does not set the direction vector correctly, causing the bullets to move unpredictably or remain stationary.

Solving the Issue

To rectify this issue, the direction vector should be calculated and normalized (converted to a unit vector) as follows:

  • Obtain the starting position and mouse position:

    <code class="py">self.pos = (x, y)
    mx, my = pygame.mouse.get_pos()</code>
  • Calculate the direction vector:

    <code class="py">self.dir = (mx - x, my - y)</code>
  • Normalize the vector:

    <code class="py">length = math.hypot(*self.dir)
    if length == 0.0:
      self.dir = (0, -1)
    else:
      self.dir = (self.dir[0]/length, self.dir[1]/length)</code>
  • Compute the angle of the vector:

    <code class="py">angle = math.degrees(math.atan2(-self.dir[1], self.dir[0]))</code>

Rotating and Updating the Bullet

Once the direction is determined, the bullet can be rotated and updated according to its velocity:

  • Rotate the bullet:

    <code class="py">self.bullet = pygame.Surface((7, 2)).convert_alpha()
    self.bullet.fill((255, 255, 255))
    self.bullet = pygame.transform.rotate(self.bullet, angle)</code>
  • Update the bullet's position:

    <code class="py">self.pos = (self.pos[0]+self.dir[0]*self.speed, 
              self.pos[1]+self.dir[1]*self.speed)</code>

Drawing the Rotated Bullet

To correctly display the rotated bullet, its bounding rectangle is used to center it at its correct position:

  • Get the rotated bullet's bounding rectangle:

    <code class="py">bullet_rect = self.bullet.get_rect(center = self.pos)</code>
  • Draw the bullet:

    <code class="py">surf.blit(self.bullet, bullet_rect)</code>

The above is the detailed content of Why Are My Pygame Bullets Not Moving Towards the Mouse?. 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