I'm attempting to move a character so that they face the mouse when I move it; I understand the concept but am completely at a loss at how to code it. At the moment, I understand how to rotate the character separately and how to move the character separately. Is it possible for me to merge the two so that I may both move and rotate my character with keys and my mouse?
These are my defined variables:
xPlayer = 25
yPlayer = 25
dxPlayer = 0
dyPlayer = 0
playerPosition = (25,25)
This is the portion that allows the image to rotate in the direction of the mouse:
go = True
while go:
position = pygame.mouse.get_pos()
screen.blit(nightBackground, (0,0))
mousePosition = pygame.mouse.get_pos()
angle = math.atan2(mousePosition[1]-(playerPosition[1]+32),mousePosition[0]-(playerPosition[0]+26))
playerRotate = pygame.transform.rotate(peterPlayer, 360-angle*57.29)
playerpos1 = (playerPosition[0]-playerRotate.get_rect().width/2, playerPosition[1]-playerRotate.get_rect().height/2)
screen.blit(playerRotate, playerpos1)
pygame.display.update()
And this is the portion for controlling my character with the keys:
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dxPlayer = -15
elif event.key == pygame.K_RIGHT:
dxPlayer = 15
elif event.key == pygame.K_UP:
dyPlayer = -15
elif event.key == pygame.K_DOWN:
dyPlayer = 15
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dxPlayer = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dyPlayer = 0
xPlayer = xPlayer + dxPlayer
yPlayer = yPlayer + dyPlayer
pygame.display.update()
Any help is greatly appreciated!