I'm trying to make a racing game with pygame (not finished) by following a tutorial on youtube. The code works totally fine, except when I pressed the arrowkey and pressed the opposite of that arrowkey really quickly, the race car gets stuck until I let the key go and press the key again. Is there any way to fix that?
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
carImg = pygame.image.load('BlackCar.png')
def car(x, y):
gameDisplay.blit(carImg, (x, y))
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.key == pygame.K_UP:
y_change = -5
if event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
x += x_change
y += y_change
gameDisplay.fill(white)
car(x, y)
pygame.display.flip()
clock.tick(60)
pygame.quit()
quit()
x_change -= 5x_change += 5inKEYDOWNandKEYUPand then it should work better. It will "cumulate both arrows and it will "remeber" previous arrow when you release other arrow. Now when you release second key then it setx_change = 0and it doen't remeber second key. - furas