Menu
CoddyTech

从地面起跳

本课属于 Coddy Pygame 学习旅程的“游戏世界”单元。第 11 课,共 36 课。

跳跃对应负速度。设置 vel_y = -15 后,玩家会向上移动 15 像素;重力每帧会抵消 1 个像素,直到玩家再次下落。这就形成了跳跃弧线。

只有在地面上才能开始跳跃。用一个标记记录玩家这一帧是否站在地面上:

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

使用 KEYDOWN 事件来处理跳跃,这样按一次就跳一次,无论按键是否一直按着:

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) 都为 True。在空中时,on_ground 为 False,因此再次按键不会有任何效果。

challenge icon

挑战

中等

让玩家从地面跳起来。

  1. 在顶部添加 JUMP = -15,并在游戏循环之前添加 on_ground = False。
  2. 每一帧,在地面检测之前设置 on_ground = False,并在地面检测中设置 on_ground = True。
  3. 按下空格键或向上键触发 KEYDOWN 时,如果 on_ground 为 True,就设置 vel_y = JUMP。

点击 “开始”并按下空格键:玩家会跳起来,然后落回地面。然后点击 “检查”。

亲手试试

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

游戏世界中的所有课

自己练习: Pygame 在线编辑器