Short Hops
Part of the Worlds section of Coddy's Pygame journey. Lesson 12 of 35.
In most platformers a quick tap gives a small hop and a long press a full jump. That lets the player choose the height of every jump.
When the jump key comes up, a KEYUP event arrives. If the player is still rising fast, slow the rise:
elif event.type == pygame.KEYUP and event.key in (pygame.K_SPACE, pygame.K_UP):
if vel_y < -4:
vel_y = -4A held key never sends KEYUP during the rise, so the jump goes its full height. A tap sends it a frame later, the speed drops to -4, and gravity turns the player round a few frames after.
The test vel_y < -4 matters. Near the top, or while falling, vel_y is above -4, and setting it to -4 there would push the player back up.
Challenge
Easy- On a
KEYUPof Space or Up, whenvel_yis below -4, setvel_y = -4. - Leave the
KEYDOWNjump as it is.
Try it yourself
import pygame
TILE = 36
FLOOR = 324
GRAVITY = 1
JUMP = -15
pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("Short Hops")
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
on_ground = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
if on_ground:
vel_y = JUMP
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
on_ground = False
if player.bottom > FLOOR:
player.bottom = FLOOR
vel_y = 0
on_ground = True
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