See How to rotate an image(player) to the mouse direction?. What you want to do depends on which part of the player (top or right etc.) should be orientated to the mouse.
Don’t compute and sum relative angles. Calculate the vector form the the player to the mouse:
player_x, player_y = # position of the player
mouse_x, mouse_y = pygame.mouse.get_pos()
dir_x, dir_y = mouse_x - player_x, mouse_y - player_y
The angle of the vector can be calculated by math.atan2
. The angle has to be calculated relative to the base orientation of the player.
e.g.
The right side of the player is orientated to the mouse:
angle = (180 / math.pi) * math.atan2(-dir_y, dir_x)
The top of the player is orientated to the mouse:
angle = (180 / math.pi) * math.atan2(-dir_x, -dir_y)
A basic alignment can be set using a correction angle. For example 45 for a player looking at the top right:
angle = (180 / math.pi) * math.atan2(-dir_y, dir_x) - 45
The method update
may look like this:
def update(self):
self.pos += self.vel * self.game.dt
mouse_x, mouse_y = pygame.mouse.get_pos()
player_x, player_y = self.pos
dir_x, dir_y = mouse_x - player_x, mouse_y - player_y
#self.rot = (180 / math.pi) * math.atan2(-dir_y, dir_x)
#self.rot = (180 / math.pi) * math.atan2(-dir_y, dir_x) - 45
self.rot = (180 / math.pi) * math.atan2(-dir_x, -dir_y)
self.image = pygame.transform.rotate(self.game.player_img, self.rot)
self.rect = self.image.get_rect()
self.rect.center = self.pos
Minimal example: repl.it/@Rabbid76/PyGame-RotateWithMouse