Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - Keys do not move sprite properly in pygame, strange behavior


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

pygame.key.get_pressed() returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key attribute of the pygame.event.Event object:

while carryOn == True:
    # [...]
    
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                my_sprite.update(50, 0)
            if event.key == pygame.K_s:
                my_sprite.update(-50, 0)
            if event.key == pygame.K_d:
                my_sprite.update(0, 50)
            if event.key == pygame.K_a:
                my_sprite.update(0, 50)

    # [...]

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.

pygame.key.get_pressed() returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key attribute of the pygame.event.Event object.

However, you must evaluate the keys in the application loop rather than the event loop:

while carryOn == True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            carryOn=False
            
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        my_sprite.update(50, 0)
    if keys[pygame.K_s]:
        my_sprite.update(-50, 0)
    if keys[pygame.K_d]:
        my_sprite.update(0, 50)
    if keys[pygame.K_a]:
        my_sprite.update(0, 50)

    # [...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...