Python Forum
[PyGame] Increasing speed while a button is held down? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Game Development (https://python-forum.io/forum-11.html)
+--- Thread: [PyGame] Increasing speed while a button is held down? (/thread-27776.html)



Increasing speed while a button is held down? - Reldaing - Jun-21-2020

Hi, I'm currently making a game on Pygame, and I want the rectangle to move 40 by 40 while the button is held,and faster and faster while it's pressed, but I could only do it once, and not while it's pressed. I think that I may need a clock but I don't know where to add it. How could I modify my code to do it? Thanks!
import pygame
width=720
height=480

screen = pygame.display.set_mode((width,height))

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((40, 40))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.x=self.rect.x
        self.y=self.rect.y
        self.direction=''

    def move(self,sens):
        if sens=='up' and player.rect.top!=0:
            player.rect.move_ip(player.x,player.y-40)

        if sens=='down' and player.rect.bottom!=height:
            player.rect.move_ip(player.x,player.y+40)
           
        if sens=='left' and player.rect.left!=0:
            player.rect.move_ip(player.x-40,player.y)
            
        if sens=='right' and player.rect.right!=width:
            player.rect.move_ip(player.x+40,player.y)
 




player = Player()
running = True
while running:

    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                player.move('up')
            elif event.key == pygame.K_s:
                player.move('down')
            elif event.key == pygame.K_a:
                player.move('left')
            elif event.key == pygame.K_d:
                player.move('right')

    screen.blit(player.image, player.rect)
    pygame.display.update()


quit()



RE: PyGame: Help with 'while button pressed' - Yoriz - Jun-21-2020

My thoughts are:
  • A variable storing the last key pressed
  • A multiplier variable that starts as 0.
  • Multipy the move amount by the multiplier.
  • Change the last key pressed to the current one at the end of the event loop.
  • If the previous key pressed is the same as the current key pressed then increase the multiplier.
  • If the previous key pressed is not the same as the current key pressed, reset the multiplier.



RE: Increasing speed while a button is held down? - Reldaing - Jun-21-2020

Ok Thanks I'll try!