繁体   English   中英

即使我已经按下它,我的键也不起作用 Python Pygame

[英]My key does not work eventhough I pressed it already Python Pygame

    import pygame, sys
    
    pygame.init()
    pygame.display.set_caption("test 1")
    
    #main Variables
    clock = pygame.time.Clock()
    window_size = (700, 700)
    screen = pygame.display.set_mode(window_size, 0, 32)
    
    #player variables
    playerx = 150
    playery = -250
    player_location = [playerx, playery]
    player_image = pygame.image.load("player/player.png").convert_alpha()
    player_rect = player_image.get_rect(center = (80,50))
    
    #button variables
    move_right = False
    move_left = False
    move_up = False
    move_down = False
    
    while True:
        screen.fill((4, 124, 32))
        screen.blit(player_image, player_location, player_rect)
    
        if move_right == True:
            playerx += 4
        if move_left == True:
            playerx -= 4
        if move_up == True:
            playery -= 4
        if move_down == True:
             playery += 4
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_d:
                    move_right = True
                if event.key == pygame.K_a:
                    move_left = True
                if event.key == pygame.K_w:
                    move_up = True
                if event.key == pygame.K_s:
                    move_down = True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d:
                    move_right = False
                if event.key == pygame.K_a:
                    move_left = False
                if event.key == pygame.K_w:
                    move_up = False
                if event.key == pygame.K_s:
                    move_down = False
    
        pygame.display.update()
        clock.tick(120)

我无法让它工作。 我按下了按钮,但它不会向上或向下 go。 当我没有为播放器使用矩形时,它运行良好。 我想要这样我也可以在 y 轴上上下移动角色。 我刚开始学习如何使用 PyGame 所以请帮助我谢谢。

当你移动玩家时,你改变了playerxplayery变量。 但是,玩家 id 被绘制到存储在player_location中的 position 上。 您必须在绘制播放器之前更新player_location

while True:
    screen.fill((4, 124, 32))
    player_location = [playerx, playery]
    screen.blit(player_image, player_location, player_rect)

    # [...]

请注意,您根本不需要player_location [playerx, playery]处绘制玩家:

while True:
    screen.fill((4, 124, 32))
    screen.blit(player_image, [playerx, playery], player_rect)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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