Python Forum
[PyGame] Increasing speed while a button is held down?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Increasing speed while a button is held down?
#1
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()
Reply
#2
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.
Reply
#3
Ok Thanks I'll try!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020