Issue
This Content is from Stack Overflow. Question asked by Quinten
I`m trying to recreate pong using python/pygame but I got stuck on the playermovement,
whenever the 2 players are moving at the same time they will lag or even stop moving.
I think this has to do with the way I read keyboard key inputs I have tried to change it several times but still no succes.
while run1v1:
clock.tick(60)
window.fill((black))
for event in pg.event.get():
keys = pg.key.get_pressed()
playerposY += (keys[pg.K_s] - keys[pg.K_w]) * speed
player2posY += (keys[pg.K_DOWN] - keys[pg.K_UP]) * speed
Solution
See How can I make a sprite move when key is held down.
pygame.key.get_pressed()
is not an event. You have do the movement in the application loop not in the event loop:
# application loop
while run1v1:
clock.tick(60)
window.fill((black))
# event loop
for event in pg.event.get():
if event.type == pg.QUIT:
run1v1 = False
# INDENTTAION
#<--|
keys = pg.key.get_pressed()
playerposY += (keys[pg.K_s] - keys[pg.K_w]) * speed
player2posY += (keys[pg.K_DOWN] - keys[pg.K_UP]) * speed
This Question was asked in StackOverflow by Quinten and Answered by Rabbid76 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.