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 = 0vel_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
Easy- Add
GRAVITY = 1at the top andvel_y = 0before the game loop. - Each frame, add
GRAVITYtovel_y, then addvel_ytoplayer.y, instead ofplayer.y += 4. - When
player.bottompassesFLOOR, setplayer.bottom = FLOORandvel_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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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