How to rotate an image(player) to the mouse direction?
Solution 1:
You have to compute the angle of the vector from the player to the mouse. get the mouse position by pygame.mouse.get_pos()
and the rectangle (pygame.Rect
) around the player:
mx, my = pygame.mouse.get_pos()
player_rect = Player_1.get_rect(topleft=(P_X,P_Y))
Calculate the vector from the player to the mouse and compute the angle of vector by math.atan2
. The y-axis needs to be reversed (-dy
) as the y-axis is generally pointing up, but in the PyGame coordinate system the y-axis is pointing down.
dx, dy = mx - player_rect.centerx, player_rect.centery - my
angle = math.degrees(math.atan2(-dy, dx)) - correction_angle
In addition, a correction angle must be deducted (- correction_angle
). The correction angle depends on the Sprite. If the Sprite
is looking to the right, the correction angle is 0: correction_angle = 0
is looking up, the correction angle is 90: correction_angle = 90
is looking to the left, the correction angle is 180: correction_angle = 180
is looking down, the correction angle is 270: correction_angle = 270
Rotate the player with pygame.transform.rotate()
by the angle around its center:
(See also How do I rotate an image around its center using Pygame?)
rot_image = pygame.transform.rotate(Player_1, angle)
rot_image_rect = rot_image.get_rect(center=player_rect.center)
Minimal example: repl.it/@Rabbid76/PyGame-RotateWithMouse
import math
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
player = pygame.image.load("player.png").convert_alpha()
# 0 - image is looking to the right
# 90 - image is looking up
# 180 - image is looking to the left
# 270 - image is looking down
correction_angle = 90
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
player_pos = window.get_rect().center
player_rect = player.get_rect(center = player_pos)
mx, my = pygame.mouse.get_pos()
dx, dy = mx - player_rect.centerx, my - player_rect.centery
angle = math.degrees(math.atan2(-dy, dx)) - correction_angle
rot_image = pygame.transform.rotate(player, angle)
rot_image_rect = rot_image.get_rect(center = player_rect.center)
window.fill((255, 255, 255))
window.blit(rot_image, rot_image_rect.topleft)
pygame.display.flip()
pygame.quit()
exit()