0

In my code, I want to move the object while the key is pressed and stop when the key is released. However, it moves only one step even when I keep the key pressed. Here is the sample code. I have printed the (x,y) values. Any suggestion? Thanks.

x = 20
y = 20

def keydown(evt):
        global x, y
        if evt.type == pygame.KEYDOWN:
                if(evt.key == pygame.K_RIGHT): x += 2.0
                if(evt.key == pygame.K_LEFT): x -= 2.0
                if(evt.key == pygame.K_UP): y += 2.0
                if(evt.key == pygame.K_DOWN): y -= 2.0
        if evt.type == pygame.KEYUP:
                if(evt.key == pygame.K_RIGHT or evt.key == pygame.K_LEFT): x = x
                if(evt.key == pygame.K_UP or evt.key == pygame.K_DOWN): y = y


while True:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        pygame.quit()
                        sys.exit()

                print(x, y)
                keydown(event)

PS: I tried this as posted somewhere in this forum (How can I make a sprite move when key is held down) but no success.

keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]: x += 2.0
if keys[pygame.K_LEFT]: x -= 2.0
if keys[pygame.K_UP]: y += 2.0
if keys[pygame.K_DOWN]: y -= 2.0
Community
  • 1
  • 1
manojg
  • 59
  • 8

1 Answers1

0
x = 20
y = 20

def keydown(evt):
        global x, y
        if(evt[pygame.K_RIGHT]): x += 2.0
        if(evt[pygame.K_LEFT]): x -= 2.0
        if(evt[pygame.K_UP]): y += 2.0
        if(evt[pygame.K_DOWN]): y -= 2.0


while True:
        keys = pygame.key.get_pressed()
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        print(x, y)
        keydown(keys)

so first off you had some code that was never really doing anything in your keydown function

if evt.type == pygame.KEYUP:
    if(evt.key == pygame.K_RIGHT or evt.key == pygame.K_LEFT): x = x
    if(evt.key == pygame.K_UP or evt.key == pygame.K_DOWN): y = y

pygame.key.get_press() returns a dictionary that maps pygame.KEY_**** to booleans. iterating through this would only give you booleans, which is not useful for you. the code i wrote instead will work by continually getting all keys pressed, and changing your X and Y based on whether or not certain keys are pressed.

if you have any more questions feel free to ask, hope this helped!

if this is still not working please post your error messages

Toolbox97
  • 76
  • 7