Im thinking about making a 2d shooting game in pygame and i want to make my player(Player_1) point to the mouse direction.I looked for a solution for hours and tried all solution i could find but none had worked so can you pls help me ?
Here's my code:
This is my player(Player_1)
I will really appreciate all help.
Best Answer-推荐答案
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:
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.
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?)
Minimal example: repl.it/@Rabbid76/PyGame-RotateWithMouse
|