简体   繁体   中英

python 3.X lagging player movement

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

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
while run1v1:
    clock.tick(60)
    window.fill((black))
    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
    for event in pg.event.get():

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM