0

Hello I'm trying to move a character with with +1 pixel every loop while a button is held.

However since Windows has a built in delay on holding down a key then simply using a code like below doesn't work. The code is meant to give a certain speed while the character is on the ground and a slower, but increasing speed if in the air.

I have read some comment about how "Using keys to directly move the character" isn't the right way to solve the problem. However I cannot figure out how to go about this.

Thankful for any help!

Key presses:

keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
    player.go_left()
if keys[pygame.K_d]:
    player.go_right()

Move character functions:

def go_left(self):
    if self.air == False:
        self.change_x = -5
    else:
        self.change_x -= 0.5
def go_right(self):
    if self.air == False:
        self.change_x = 5
    else:
        self.change_x += 0.5
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Zoler1337
  • 108
  • 5
  • 1
    Maybe the `pygame.key.set_repeat` function can help you. If not, start the movement at `KEYDOWN` and stop it at `KEYUP`. – Wups Jan 07 '22 at 11:32
  • 1
    *"However since Windows has a built in delay "* - No the window has no delay. This is either a bug in your code or related to your system. `pygame.key.get_pressed()` reacts immediately. See [How can I make a sprite move when key is held down](https://stackoverflow.com/questions/9961563/how-can-i-make-a-sprite-move-when-key-is-held-down) and try the code snippets there, which work well. e.g.: run https://replit.com/@Rabbid76/PyGame-ContinuousMovement#main.py – Rabbid76 Jan 07 '22 at 12:06
  • I'm not talking about the window but the Operative system Windows, sorry for the confusion. – Zoler1337 Jan 07 '22 at 12:10
  • If you try to type in this text window and hold down a button, first it will only type one letter, then after a short delay it will type a continous flow of letters. The same principle applies to my code and what I would like to fix. – Zoler1337 Jan 07 '22 at 12:15
  • 1
    @Zoler1337 Yes I know, but this is not the case when using `pygame.key.get_pressed()`. This function gives the current state of the key. The `KEYDOWN` event however will be delayed. – Rabbid76 Jan 07 '22 at 12:20
  • 1
    @Zoler1337 Where do you call `pygame.key.get_pressed()`? It it is not an event. Do not call it in the event loop. See [How can I make a sprite move when key is held down](https://stackoverflow.com/questions/9961563/how-can-i-make-a-sprite-move-when-key-is-held-down) – Rabbid76 Jan 07 '22 at 12:22
  • Ok that is probably the problem thank you! I replaced KEYDOWN with key.get_pressed() just before and I put it in the event-loop. I'll give it a try soon – Zoler1337 Jan 07 '22 at 12:24

0 Answers0