David Mustea
David Mustea

Reputation: 67

Player getting back in initial position when I try to move it Pygame

When I move the player he moves 10 pixels while I am holding down right arrow and goes back to initial postion when I release the key. Btw, u don't need to tell me the he moves to the left when I press right, I know that :)

This is code:

import pygame



pygame.init()

WIDTH = 1000
HEIGHT = 1000
screen = pygame.display.set_mode([WIDTH,HEIGHT])
clock = pygame.time.Clock()

WHITE = (255,255,255)
def ecranAlb():
    screen.fill(WHITE)

def player():
    playerImg = pygame.image.load('jucator.png')
    WIDTHplayer = 150
    HEIGHTplayer = 130
    playerImg = pygame.transform.scale(playerImg,(WIDTHplayer,HEIGHTplayer))
    Xplayer = 500
    Yplayer = 500
    

    vel = 10

    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT]:
        Xplayer -= vel

    
    screen.blit(playerImg,(Xplayer,Yplayer))   

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    ecranAlb()
    player()
    pygame.display.flip()



pygame.quit()

Upvotes: 2

Views: 169

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

The position of the player is continuously set in the application loop within the player function:

def player():
   # [...]

   Xplayer = 500
   Yplayer = 500

You must initialize the player position before the application loop outside of the function. Use the global statement to change the variable in global namespace within the function:

playerImg = pygame.image.load('jucator.png')
WIDTHplayer = 150
HEIGHTplayer = 130
playerImg = pygame.transform.scale(playerImg,(WIDTHplayer,HEIGHTplayer))
Xplayer = 500
Yplayer = 500
vel = 10

def player():
    global Xplayer, Yplayer  
    
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:
        Xplayer -= vel
 
    screen.blit(playerImg,(Xplayer,Yplayer))

Upvotes: 4

Related Questions