0

I am writing a top-down shooter game. The player should hold a gun, and I want it to point in the direction of the mouse. Here is the code I have to calculate the angle it needs to be displayed:

        
        rel_x, rel_y = target_x - self.x, target_y - self.y
        self.angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
        
        self.weapon_copy = pygame.transform.rotate(self.primary_weapon.image, self.angle)
        
        display.blit(self.weapon_copy, (self.x + self.primary_weapon.x_offset -
                                        int(self.primary_weapon.image.get_width() / 2 + display_scroll[0]),
                                        self.y + self.primary_weapon.y_offset - int(self.weapon_copy.get_height() / 2)
                                        - display_scroll[1]))

It works, but there is one issue: If I am pointing the gun to the right of the player, it looks normal, but if I point it to the left of the player, the gun still points towards the mouse, but it becomes upside-down (all my weapon images show the gun pointing to the right by default). What code can I add to make the gun right-side-up at all times?

Jerry Cui
  • 3
  • 2
  • At some point the image has to flip on the vertical axis, presumably when the cursor is above and below the player. You could add an if-statement that applies a flipping transformation to the image when the following condition is met: 90 deg >= current_angle >= 270 deg. – Paul M. Oct 29 '21 at 23:10

1 Answers1

0

The function math.atan2 returns an angle value that ranges from -PI to +PI, what you can do to solve your problem is check if value is negative and then subtract it from 360, take a look at it:

self.angle = (180 / math.pi) * math.atan2(rel_y, rel_x)

if self.angle < 0:
    self.angle = 360 + self.angle
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20