I am new to pygame and I am trying to make pong in order to learn it. I am trying to make smooth controls so that holding down an arrow will work, but it is not working right now.
import sys, pygame
pygame.init()
size = (500, 350)
screen = pygame.display.set_mode(size)
x = 1
xwid = 75
yhei = 5
pygame.key.set_repeat(0, 500)
while True:
vector = 0
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
vector = 4
elif event.key == pygame.K_LEFT:
vector = -4
pygame.draw.rect(screen,(255,255,255),(x,size[1] - yhei,xwid,yhei),0)
pygame.display.update()
screen.fill((0,0,0))
x += vector
if x <= 0:
x = 0
elif x >= size[0] - xwid:
x = size[0] - xwid
why does this not work for holding down the left or right arrows?
If you set the
delay
parameter to0
, key repeat will be disabled. The documentation isn't quite clear about that:Emphasis mine.
You could set the
delay
to1
, and it would work as expected:But note that you should not use
set_repeat
and thepygame.KEYDOWN
event to implement movement. If you do, you won't be able to observe real single key strokes, since if the player presses a key, a whole bunch ofpygame.KEYDOWN
events would be created.Better use
pygame.key.get_pressed()
. Have a look at his minimal example:I know what do you mean. Try this: