Menu
CoddyTech

Falling With Gravity

Part of the Worlds section of Coddy's Pygame journey. Lesson 10 of 35.

The hero in the window drops at a steady 4 pixels a frame, like a lift. Real things speed up as they fall. Keep the player's vertical speed in a variable, and grow it every frame:

vel_y += GRAVITY
player.y += vel_y
if player.bottom > FLOOR:
    player.bottom = FLOOR
    vel_y = 0

vel_y is the speed in pixels a frame; positive is down. GRAVITY = 1 adds one to it every frame, so the player falls 1, then 2, then 3 pixels, and so on.

The floor here is a line at FLOOR = 324, the top of the grass. When the player passes it, put its bottom on the line and stop the fall. The next chapter replaces this line with real platforms.

The player is the image's Rect: player_img.get_rect(topleft=(264, 40)) is a 48 by 48 Rect at that spot, and screen.blit(player_img, player) draws the image there.

challenge icon

Challenge

Easy
  1. Add GRAVITY = 1 at the top and vel_y = 0 before the game loop.
  2. Each frame, add GRAVITY to vel_y, then add vel_y to player.y, instead of player.y += 4.
  3. When player.bottom passes FLOOR, set player.bottom = FLOOR and vel_y = 0.

Try it yourself

import pygame

TILE = 36
FLOOR = 324

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))

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

    player.y += 4
    if player.bottom > FLOOR:
        player.bottom = FLOOR

    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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Worlds

Practice on your own: Pygame playground