I am trying to implement a functionality where my character on the screen is movable by holding down the WASD keys, while pressing spacebar should cause my character to attack. The user shouldn't be able to hold the spacebar in order to attack, while simultaneously being able to hold down the WASD keys to move. This implementation causes the expected behaviour for attacks, but it causes the movement to also be activated by pressing down a key, thus making it impossible to hold down WASD to move:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
pos_y += speed //change y-position by the value of speed
if pressed[pygame.K_a]:
pos_x -= speed
if pressed[pygame.K_s]:
pos_y -= speed
if pressed[pygame.K_d]:
pos_x += speed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
attack() //execute attack logic - irrelevant for this example
Is there a way to differentiate whether the key is held down or just pressed down?