Jump From the Ground
Part of the Worlds section of Coddy's Pygame journey. Lesson 11 of 35.
A jump is a negative speed. Set vel_y = -15 and the player moves up 15 pixels; gravity takes 1 off every frame until it falls again. That gives the arc.
A jump should start only from the ground. Keep a flag that says whether the player stood on the floor this frame:
vel_y += GRAVITY
player.y += vel_y
on_ground = False
if player.bottom > FLOOR:
player.bottom = FLOOR
vel_y = 0
on_ground = TrueUse the KEYDOWN event for the jump, so one press is one jump, whether the key is held or not:
elif event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
if on_ground:
vel_y = JUMPevent.key in (pygame.K_SPACE, pygame.K_UP) is True for either key. In the air on_ground is False, so a second press does nothing.
Challenge
Medium- Add
JUMP = -15at the top andon_ground = Falsebefore the game loop. - Each frame, set
on_ground = Falsebefore the floor test andon_ground = Trueinside it. - On a
KEYDOWNof Space or Up, whenon_groundis True, setvel_y = JUMP.
Try it yourself
import pygame
TILE = 36
FLOOR = 324
GRAVITY = 1
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Gravity")
clock = pygame.time.Clock()
background = pygame.image.load("assets/backgrounds/clouds.png").convert_alpha()
grass_img = pygame.image.load("assets/images/grass.png").convert_alpha()
player_img = pygame.image.load("assets/images/player.png").convert_alpha()
player = player_img.get_rect(topleft=(264, 40))
vel_y = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 4
if keys[pygame.K_RIGHT]:
player.x += 4
vel_y += GRAVITY
player.y += vel_y
if player.bottom > FLOOR:
player.bottom = FLOOR
vel_y = 0
for y in range(0, 360, 72):
for x in range(0, 576, 72):
screen.blit(background, (x, y))
for x in range(0, 576, TILE):
screen.blit(grass_img, (x, FLOOR))
screen.blit(player_img, player)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Worlds
1Maps from Text
A Level in TextRows and ColumnsLetters With MeaningsWhere the Player StartsOne Screen at a Time3Gravity and Jumping
Falling With GravityJump From the GroundShort HopsA Top Falling SpeedJump BufferPractice on your own: Pygame playground