按一次多个键让我的性格斜走(Press multiple keys at once to get m

2019-07-31 20:34发布

我遇到的问题是,我试图让当用户按下任一K_UP键和K_RIGHT键或K_UP键和K_DOWN关键,我的性格上的屏幕角移动等。这里是我的游戏人物动作的代码(事件处理):

1. #Event Handling
2. for event in pygame.event.get():
3.     if event.type == pygame.QUIT: 
4.         sys.exit()
5.     elif (event.type == KEYDOWN):
6.         if ((event.key == K_ESCAPE)
7.             or (event.key == K_q)):
8.             sys.exit()
9.         if (event.key == K_UP):
10.            self.char_y = self.char_y - 10
11.        if (event.key == K_DOWN):
12.            self.char_y = self.char_y + 10
13.        if (event.key == K_RIGHT):
14.            self.char_x = self.char_x + 10
15.        if (event.key == K_LEFT):
16.            self.char_x = self.char_x - 10

Answer 1:

你可以通过做pygame.key.get_pressed() :

keys = pygame.key.get_pressed()

if keys[K_LEFT]:
    self.char_x += 10

if keys[K_RIGHT]:
    self.char_x -= 10

if keys[K_UP]:
    self.char_y -= 10

if keys[K_DOWN]:
    self.char_y += 10


文章来源: Press multiple keys at once to get my character to move diagonally