0

I am new to pygame and currently I am learning about Keyboard input (self-taught). I have used Sentdexs code from his tutorial, but when I press the left or right arrow, my rect doesn't move. I tried to print something to cmd when I press the key and it's working. But when I try to move a rect, nothing happens. (Also there are no error messages in the cmd)

Here's the code:

class Rect:
    def __init__(self, x, y, w, h, xs, ys):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.xs = xs
        self.ys = ys
    
    def draw(self):
        pygame.draw.rect(win, black, (self.x, self.y, self.w, self.h))
    
    def move(self):
        self.x += self.xs
        self.y += self.ys

plX = 30
plY = 30
plW = 100
plH = 20
plSx = 0 # player speed on X
plSy = 0 # player speed on Y
r1 = Rect(plX, plY, plW, plH, plSx, plSy)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                plSx = -5
            elif event.key == pygame.K_RIGHT:
                plSx = 5
                
    r1.move()
    win.fill(bg_color)
    r1.draw()
    pygame.display.update()
StevenLukic
  • 26
  • 1
  • 2

1 Answers1

0

I have found the fix myself.

Instead of

if event.type == pygame.KEYDOWN:
             if event.key == pygame.K_LEFT:
                 plSx = -5
             elif event.key == pygame.K_RIGHT:
                 plSx = 5

I put

if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                r1.xs = -5
            elif event.key == pygame.K_RIGHT:
                r1.xs = 5

And now it's working.

StevenLukic
  • 26
  • 1
  • 2