Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Press multiple keys at once to get my character to move diagonally

The problem I'm having is that I'm trying to make my character move diagonally on screen when a user presses either the K_UP key and K_RIGHT key or the K_UP key and K_DOWN key, etc. Here is my code for character movement (event handling):

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
like image 340
David Avatar asked Sep 23 '12 21:09

David


1 Answers

You can do it via 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
like image 83
BlackBear Avatar answered Oct 13 '22 19:10

BlackBear