The smooth movement of the player in pygame

I am using the pygame library. The following is the pseudo code for event handling for the player:

#generates multiple events for keys that are held down
pygame.key.set_repeat(30,30)

for event in pygame.event.get()

   nextPos = currentPos

   if(keyUp):
       if event.key == w :
         key_w = false
       #do the same for s, a and d

   if(keyDown):
       if event.key == w:
         key_w = true
       #same for s,a and d

   if(key_w):
      #update nextPos

   #do same for key_s, key_a and key_d

   currentPos = nextPos

The problem is that sometimes when I move the mouse on the screen and I simultaneously press a key while processing mouse events, the key events are queued and these multiple keystrokes are executed together so that the player seems to jump a huge distance.

This problem does not occur if I do not move the mouse at all.

+3
source share
4 answers

Update my answer:

I checked my game code to see how I handle the keys for each frame, and it seems that I am not getting key information from the events, but use pygame.key.get_pressed ():

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gl.loop_main_loop = False # exit main loop and terminate 
    keys = pygame.key.get_pressed()
    for key, state in enumerate(keys):
        if (key in self.key_handlers) and state:
            self.key_handlers[key]() # call key handler proc

, . , .

- , .


, , , , , (, WSAD) . , , .

mousemotion- , , pygame.mouse.get_pos() pygame.mouse.get_pressed().

, ( pygame ) .

+1

...

cooridinate...

x = 300
y = 300
pX = 0
pY = 0

x y , , pX pY .

...

for event in pygame.event.get(): 
    if event.type == pygame.QUIT: 
        sys.exit(0)

    if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
        pX -= 2
    if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
        pX += 2
    if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
        pY -= 2
    if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
        pY += 2       

    if event.type == pygame.KEYUP and event.key == pygame.K_LEFT:
        pX += 2
    if event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:
        pX -= 2
    if event.type == pygame.KEYUP and event.key == pygame.K_UP:
        pY += 2
    if event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
        pY -= 2

, , , ...

x += pX
y += pY
+1

, , , , ?

0

pygame.event.get()

, pygame.key.get_pressed()

:

while True:
    keys = pygame.key.get_pressed()
    if keys[K_a]:
        player.pos.x -= 10
    if keys[K_d]:
        player.pos.x += 10
    if keys[K_w]:
        player.pos.y -= 10
    if keys[K_s]:
        player.pos.y += 10

, .

0

Source: https://habr.com/ru/post/1780018/


All Articles