My player is not moving correctly, when the key is held down, it should move continuoulsy, but only moves once

Viewed 33

I'm trying to write something simple in pygame, but this is something I don't understand. I'm trying to add moving but it's not continuous. I press and hold the key but the key only goes through 1 x_change

import pygame, sys
from pygame.locals import *

pygame.init()
gDis=pygame.display.set_mode((400,300))

Black=(0,0,0)
White=(255,255,255)
Red=(255,0,0)
Blue=(0,0,255)
Silver=(192,192,192)

clock=pygame.time.Clock()
x=195
y=270
wid=20
hght=20
speed=5

x_change=0
y_change=0
left=False
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == K_LEFT:
                x_change-=5
            

                
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                            x_change=0

        x+=x_change

        gDis.fill(Black)

        pygame.draw.rect(gDis, Silver, (x, y, wid, hght))
        clock.tick(60)

    
    pygame.display.update()
1 Answers

It is a matter of Indentation. You must move and draw the player in the application loop instead of the event loop:

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == K_LEFT:
                x_change = -5
            
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0

    # INDENTATION

    #<--|

    x += x_change

    gDis.fill(Black)
    pygame.draw.rect(gDis, Silver, (x, y, wid, hght))
    pygame.display.update()
    clock.tick(60)
Related