How To Fix Infinite Jump Bug In Pygame?
I am trying to make a game, but you can keep spamming 'w' (jump) for infinite height which is really bad when you are trying to make a platformer game. This is all my code: GRAVITY
Solution 1:
You can define a on_ground
variable that you set to True
if the player touches the ground. When the user wants to jump (presses 'w') you first check if on_ground:
and then change the y_change
and set on_ground
to False
.
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
GRAVITY = .5
player_img = pygame.Surface((30, 50))
player_img.fill((40, 120, 200))
x = 100
y = 500
x_change = 0
y_change = 0
on_ground = False
diedorgameover = Falsewhilenot diedorgameover:
foreventin pygame.event.get():
ifevent.type == pygame.QUIT:
diedorgameover = True
elif event.type == pygame.KEYDOWN:
ifevent.key == pygame.K_a:
x_change = -5
elif event.key == pygame.K_d:
x_change = 5
elif event.key == pygame.K_s:
y_change = 5
elif event.key == pygame.K_w:
# Only jump if the player ison the ground.
if on_ground:
y_change = -12
on_ground = False
elif event.type == pygame.KEYUP:
ifevent.key == pygame.K_a orevent.key == pygame.K_d:
x_change = 0
y_change += GRAVITY
x += x_change
y += y_change
# If the player ison the ground.
if y >= gameDisplay.get_height() - 68:
y = gameDisplay.get_height() - 68
y_change = 0
on_ground = True
gameDisplay.fill((30, 30, 30))
gameDisplay.blit(player_img, (x, y))
pygame.display.update()
clock.tick(60)
pygame.quit()
Also delete these lines, otherwise the player can stop while in the air if the key is released:
ifevent.key == pygame.K_s orevent.key == pygame.K_w:
y_change = 0
Post a Comment for "How To Fix Infinite Jump Bug In Pygame?"