I'm porting a game from Scratch to Pygame, in hopes of learning more about Pygame.
I got the movement down, it's a smooth type of movement where you can slide around and I'm setting the variables x and y to the player x and y. And I plugged the x and y to the blit to put the player in the scene, and it works just fine.
The problem is when I try to get the player to look at the mouse pointer while he moves around. I already have a function to rotate the player to the mouse pointer and it also works just fine, but when I put that function into the loop, it seems to work fine but the further right you go the less accurate it gets.
I have no idea why it does that, but I'm very annoyed since this is the only thing hindering my progress.
import pygame
import keyboard
import math
pygame.init()
width = 1920
height = 1080
x, y = 0,0
speedY = 0
speedX = 0
FPS = 60
fpsClock = pygame.time.Clock()
pygame.key.set_repeat(16,16)
screen = pygame.display.set_mode([width, height])
player = pygame.image.load("images/player.png")
player_center = (
x+(width-player.get_width())/2,
y+(height-player.get_height())/2
)
print(player_center)
player_pos = (x,y)
cursor_pos = list(screen.get_rect().center)
mousec = pygame.image.load("images/mousec.png")
def playerMove(): #this is the player move script
global speedY
global rect
global speedX
global x
global y
speedY = speedY + int(keyboard.is_pressed('s'))-int(keyboard.is_pressed('w')) * 0.9
speedY = speedY * 0.9
y += speedY
speedX = speedX + int(keyboard.is_pressed('d'))-int(keyboard.is_pressed('a')) * 0.9
speedX = speedX * 0.9
x += speedX
def playerRotate(): #this is the script to make the player look at the mouse pointer
global player_rect
global player
global player_pos
global mousec
global pos
global rotimage
global angle
global rect
player_rect = player.get_rect(center = (player_pos))
pos = pygame.mouse.get_pos()
screen.blit(mousec, (pos))
angle = 360-math.atan2(pos[1]-300,pos[0]-400)*180/math.pi
rotimage = pygame.transform.rotate(player,angle)
rect = rotimage.get_rect(center=(400,300))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
playerRotate()
playerMove()
screen.fill((255, 255, 255))
screen.blit(rotimage, (x,y))
pygame.display.flip()
fpsClock.tick(FPS)
# Done! Time to quit.
pygame.quit()