My player is blitted exactly in the middle of the screen. However when I move the player right and left even though the camera follows the player image, the player rect moves faster than the image itself and goes outside screen at some point. I tried many things and I'm not sure what is wrong here. I've been stuck in here for hours, please help me.
import pygame,sys
pygame.init()
windowsize=(800,600)
display=pygame.display.set_mode(windowsize)
screen=pygame.Surface((600,400))
main_running=True
playerrect = pygame.Rect(300 ,300, 32, 32)
playeridle=[]
for i in range(1,17):
playeridle.append(pygame.image.load("player\playeridle (%s).png"%i))
movingleft=False
movingright=False
jump=False
true_scroll=[0,0]
timer=0
stay=0
while main_running:
screen.fill((0,0,0))
true_scroll[0] += (playerrect.x-true_scroll[0]-300)/20
true_scroll[1] += (playerrect.y-true_scroll[1]-300)/20
scroll = true_scroll.copy()
scroll[0] = int(scroll[0])
scroll[1] = int(scroll[1])
playerx=playerrect.x-scroll[0]
playery=playerrect.y-scroll[1]
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
movingleft=True
if event.key==pygame.K_RIGHT:
movingright=True
if event.key==pygame.K_SPACE:
jump=True
if event.type==pygame.KEYUP:
if event.key==pygame.K_LEFT:
movingleft=False
if event.key==pygame.K_RIGHT:
movingright=False
if event.key==pygame.K_SPACE:
jump=False
player_movementx=0
player_movementy=0
if movingleft:
player_movementx=-5
if movingright:
player_movementx=+5
player_movementy+=0.2
if player_movementy>=7:
player_movementy=7
playerrect.x+=player_movementx
playerrect.y+=player_movementy
rect=pygame.Rect(0-scroll[0],300-scroll[1],600,50)
pygame.draw.rect(screen,(0,255,255),rect)
#playeranimations
timer+=1
if timer>=5:
stay+=1
timer=0
if stay>=16:
stay=0
screen.blit(playeridle[stay],(playerx,playery))
pygame.draw.rect(screen,(255,0,0),playerrect,1)
pygame.time.delay(30)
display.blit(pygame.transform.scale(screen, windowsize), (0, 0))
pygame.display.update()