Home >Backend Development >Python Tutorial >Why Are My Pygame Bullets Not Moving Towards the Mouse?
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.
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.
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>
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>
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!