1
votes

I'm just getting started with Python and Pygame. I was following this lesson (GitHub) on how to make tile-based game. I want to implement mouse tracking, so player sprite will always look where mouse is pointed.

The game has Camera class which offsets all sprites when player moves. I managed to do mouse tracking, but currently it shows me where it is placed on 1024 * 768 screen, while player is positioned for example on 2000 * 1000. Result: player is looking from his 2000 * 1000 position to some place 'inside' that screen.

Lesson (GitHub)

I want my mouse position to be shifted by the same number of pixels, so it always stays inside player camera.

1

1 Answers

2
votes

Use

mousex, mousey = pygame.mouse.get_pos()

Now you need to calculate the angle of rotation in order to rotate your player to look at the mouse position.

First, calculate a vector that it's direction points towards the mouse position.

x = mousex - player.position.x
y = mousey - player.position.y

This results in a vector (x,y) which its direction points toward the mouse position. Why? Because when you have two vectors, in this case, a(mousex,mousey) and b(player.position.x, player.position.y),

the mathematics tells us that if you subtract b from a then you are creating another vector quantity that its length is the distance from a to b and its direction point's from b to a

Now calculate the angle (In radians)

angle = math.atan2( x, y)

Now you need to convert the angle to degrees instead of radians because the next method we are going to use must use an angle in degrees.

angle = (180 / math.pi) * (-angle) 

Now rotate the image using pygame.transform.rotate()

rotated_image = pygame.transform.rotate(your_player_image, int(angle))

Here is important to note, that you need to use the original image which you loaded using pygame.image.load() and not the one you are using to blit the player.

Now apply the new image to the player:

player.image = rotated_image