Reputation: 25
EDIT NO. 2
I did a second event loop within the function to check if there is a KEYUP event, and it works now. Thanks everyone who commented!
EDIT
So I've separated the display part from the moving thing and realised that it actually wasn't taking any new inputs from the keyboard, so it didn't know that pg.K_s wasn't pressed anymore, but now I don't know how to get the key_up event from within my function. Should I use event.get again?
I'm trying to make a game in Pygame where you use WASD to control the character. I wanted everything to be contained in different classes and functions, so I moved the character moving out of the main loop and into a function. Unfortunately, now whenever I press any WASD key, the sprite just goes in that direction infinitely and creates a runtime error.
def moving(self):
counter = 0
loop = pg.key.get_pressed()
for i in range(0, len(loop)):
if loop[i] == 1:
counter += 1
else:
continue
while counter == 1:
pressed = pg.key.get_pressed()
if pressed[pg.K_w]:
if (self.y - 3) >= 0:
self.y -= 3
elif pressed[pg.K_a]:
if (self.x - 3) >= 0:
self.x -= 3
elif pressed[pg.K_s]:
if (self.y + 3) <= 238:
self.y += 3
elif pressed[pg.K_d]:
if (self.x + 3) <= 360:
self.x += 3
self.display.fill((0, 0, 0))
self.display.blit(self.justin, (self.x, self.y))
pg.display.flip()
clock = pg.time.Clock()
clock.tick(100)
counter = 0
loop = pg.key.get_pressed()
for i in range(0, len(loop)):
if loop[i] == 1:
counter += 1
else:
continue
Here's the code where the moving function is called:
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.display.quit()
pg.quit()
elif event.type == pg.KEYDOWN:
if (event.key == pg.K_w or event.key == pg.K_a
or event.key == pg.K_s or event.key == pg.K_d):
self.moving()
I just honestly don't know where to go from this - as soon as a button stops being pressed, counter should stay at 0, and so the while loop would close, but it just infintely sends the sprite to the edge of the screen.
Upvotes: 1
Views: 989
Reputation: 161
assuming you're trying to make the character move continuously while the mouse button is held down (if you want to make it move step by step then simply check the keys individually and add/subtract to the x & y), you would be best served abandoning the counter and instead, outside your event loop placed something like this:
keys=pg.key.get_pressed()
if keys[pg.K_w]:
if x >= 0: x -= 3
if keys[pg.K_s]:
if x <= 360: x += 3
if keys[pg.K_a]:
if y >= 0: y -= 3
if keys[pg.K_d]:
if y <= 238: y += 3
Upvotes: 1