Search code examples
pythonspritepygame

Pygame Making A Sprite Face The Mouse


Im New To Pygame But Kinda OK On Python, Im Creating A Zombie Shooting Game With an overhead view.
I managed to make the character move when pressing the arrow keys. But now i need to get the player to FACE the mouse/cursor without clicking the screen all the time.
Any Help?


Solution

  • for event in pygame.event.get():
        if event.type == MOUSEMOTION:
            mousex, mousey = event.pos
            # build a vector between player position and mouse position
            moveVector = (mousex-playerx, mousey-playery)
    
            """
            compute the angle of moveVector from current vector that player is facing (faceVector).
            you should be keeping and updating this unit vector, with each mouse motion
            assume you have initial facing vector as (1,0) - facing East
            """
    
            # compute angle as in [1]
    
            # rotate the image to that angle and update faceVector
    

    [1] - How to Find the Angle Between Two Vectors: http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm

    Your image may lose quality when rotated at a small angle. It's discussed in Pygame documentation page: http://pygame.org/docs/ref/transform.html#pygame.transform.rotate