I tried using something like this but it did not work.
while running:
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
y1 -= 1
i
There are two ways to check for key input, either if they're in the event queue or checking their current state.
Keys are put into the event queue when they're pressed or realesed, so you cannot directly tell if a key is held or not. There are two ways around this:
Call pygame.key.set_repeat(True)
before you enter the main loop. This will repeatedly put the KEYDOWN event into the event queue, as long as it's held.
Introduce a velocity variable. Set the velocity to some speed when the user press down the key, and set the velocity to 0 when the user lift the key.
For example:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
velocity_x = -5
elif event.key == pygame.K_RIGHT:
velocity_x = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
velocity_x = 0
elif event.key == pygame.K_RIGHT:
velocity_x = 0
position_x += velocity_x
You get the current state of the keys by calling pygame.key.get_pressed()
. You have to call one of the functions in pygame.event
in order for pygame to do some required internal actions, so use pygame.event.pump()
if you don't want to use the event queue. Your OS will think pygame has crashed if you don't, resulting in the game being unresponsive. Although, you usually want to handle the pygame.QUIT
event, so the user can quit.
pygame.event.pump()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
position_x -= 5
elif keys[pygame.K_RIGHT]:
position_x += 5
Try adding the keys to your pygame for loop. So it should look something like this...
while running:
for event in pygame.event.get():
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
y1 -= 1
if keys[pygame.K_DOWN]:
y1 += 1
One solution to this problem would be to use set_repeat
function
pygame.key.set_repeat(True)
This will generate multiple KEYDOWN
events.