Menu
CoddyTech

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 = True

Use 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 = JUMP

event.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 icon

Challenge

Medium
  1. Add JUMP = -15 at the top and on_ground = False before the game loop.
  2. Each frame, set on_ground = False before the floor test and on_ground = True inside it.
  3. On a KEYDOWN of Space or Up, when on_ground is True, set vel_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

Practice on your own: Pygame playground