Menu
CoddyTech

一次只处理一个坐标轴

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

你的碰撞代码会移动并修正 x,然后移动并修正 y。这个起始代码会同时移动两个轴,并且只修正一次。按“开始”,然后向右走:玩家会沿着地面向后弹回。

player.x += dx
vel_y = min(vel_y + GRAVITY, MAX_FALL)
player.y += vel_y
on_ground = False
for wall in walls:
    if player.colliderect(wall):
        if dx > 0:
            player.right = wall.left
        elif dx < 0:
            player.left = wall.right
        if vel_y > 0:
            player.bottom = wall.top
            on_ground = True
        elif vel_y < 0:
            player.top = wall.bottom
        vel_y = 0

站在地面上时,重力会让玩家每帧向下移动 1 像素,进入地面。同一帧内向右移动时,玩家会与下方的地砖重叠,代码无法判断重叠的原因。它看到 dx > 0,就会把玩家的右侧放到那块地砖的左侧:沿着地面向后退。

一次重叠,两次移动,却无法知道是哪次移动导致的。每次只沿一个轴移动时,每次重叠都只有一个原因。沿 x 轴移动后,玩家还没有进入地面,所以只有真正的墙壁会挡住它。沿 y 轴移动后,重叠就只能是沿 y 轴移动造成的。

challenge icon

挑战

中等

每次只移动一个轴,修复吸附问题。

  1. 拆分移动:player.x += dx,并遍历 walls,只修正 x 轴。
  2. 然后处理重力、player.y += vel_y、on_ground = False,再进行第二次循环,只修正 y 轴。

按“开始”并向右走:角色会沿着地面平稳移动。然后点击“检查”。

亲手试试

import pygame

TILE = 36
SPEED = 4
GRAVITY = 1
JUMP = -15
MAX_FALL = 12

LEVEL = [
    "................",
    "................",
    "................",
    "....P.....###...",
    "................",
    "................",
    "...####.........",
    "............#...",
    "#.......#...#..#",
    "################",
]

pygame.init()
screen = pygame.display.set_mode((576, 360))
pygame.display.set_caption("One Axis at a Time")
clock = pygame.time.Clock()

background = pygame.image.load("assets/backgrounds/clouds.png").convert_alpha()
block_img = pygame.image.load("assets/images/block.png").convert_alpha()
player_img = pygame.image.load("assets/images/player.png").convert_alpha()

walls = []
for row, line in enumerate(LEVEL):
    for col, char in enumerate(line):
        if char == "#":
            walls.append(pygame.Rect(col * TILE, row * TILE, TILE, TILE))
        elif char == "P":
            start = (col * TILE + TILE // 2, row * TILE + TILE)

player = player_img.get_rect(midbottom=start)
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
        elif event.type == pygame.KEYUP and event.key in (pygame.K_SPACE, pygame.K_UP):
            if vel_y < -4:
                vel_y = -4

    keys = pygame.key.get_pressed()
    dx = 0
    if keys[pygame.K_LEFT]:
        dx -= SPEED
    if keys[pygame.K_RIGHT]:
        dx += SPEED

    player.x += dx
    vel_y = min(vel_y + GRAVITY, MAX_FALL)
    player.y += vel_y
    on_ground = False
    for wall in walls:
        if player.colliderect(wall):
            if dx > 0:
                player.right = wall.left
            elif dx < 0:
                player.left = wall.right
            if vel_y > 0:
                player.bottom = wall.top
                on_ground = True
            elif vel_y < 0:
                player.top = wall.bottom
            vel_y = 0

    for y in range(0, 360, 72):
        for x in range(0, 576, 72):
            screen.blit(background, (x, y))
    for wall in walls:
        screen.blit(block_img, wall)
    screen.blit(player_img, player)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

游戏世界中的所有课

自己练习: Pygame 在线编辑器