0

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!

Student
  • 39
  • 1
  • 11
  • 1
    It's hard to know what the problem is when you post small chunks of your code. Create a [mcve] and we'll get a much better context of your problem. If you both know how to move a sprite and how to rotate it, then it shouldn't be any problem to do both. You should be able to just move it, rotate it, and then update the screen (in that order). The code you've provided doesn't really show what `xPlayer` and `yPlayer` is used for so that might be were a problem occurs. – Ted Klein Bergman Jun 09 '17 at 09:34
  • Take a look at [this example](https://stackoverflow.com/a/36879101/6220679). – skrx Jun 09 '17 at 09:38

0 Answers0