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:
import pygame, sys, os
from pygame.locals import *
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
#Exit settings
def quit():
pygame.quit()
sys.quit()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
quit()
#IDS
CLOCK=pygame.time.Clock()
FPS=120
DS=pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("Shooting simulator")
W,H=DS.get_size()
P_X=W/2-50
P_Y=H/2-50
#Colors
Red=pygame.Color("#FF0000")
Blue=pygame.Color("#0000FF")
Green=pygame.Color("#00FF00")
Black=pygame.Color("#000000")
White=pygame.Color("#FFFFFF")
#IGT(in game things)
Player_1=pygame.image.load("Img/Player_1.png").convert()
def game_loop():
while True:
events()
DS.fill(White)
DS.blit(Player_1,(P_X,P_Y))
pygame.display.flip()
game_loop()
I will really appreciate all help.
Get the mouse position by
pygame.mouse.get_pos()
and the rectangle (pygame.Rect
) around the player:Calculate the angle of the players center point to the mouse position by
math.atan2
:Rotate the player around its center by
pygame.transform.rotate()
:(See also How do I rotate an image around its center using Pygame?)
Furthermore, use
.convert_alpha()
for per pixel alpha.See the example:
Here is a simple block of code that you can use to help. It uses some trigonometry and assumes the following are defined before: elsie is the player
This block should come directly after you detect keys, and should come before drawing the player, in this case, elsie.