hudsons1033
hudsons1033

Reputation: 23

How can I handle two keys, each with their own intervals, in pygame

How do I make it so if I have the space bar and the "a" key held down at the same time, the player moves left (the effect of pressing the a key) every 10 milliseconds and shoots (the effect of pressing the space bar) every 1000 milliseconds? Is this possible? Thanks in advance!

Upvotes: 0

Views: 42

Answers (1)

amacleod
amacleod

Reputation: 1560

You could track time for each of moving and shooting separately, and then when you check for the relevant keys, only allow the action if it happened far enough in the past.

now = pygame.time.get_ticks()
if pressed(K_A) and now - when_moved > 10:
    when_moved = now
    move_left()
if pressed(K_SPACE) and now - when_shot > 1000:
    when_shot = now
    shoot()

Upvotes: 1

Related Questions