如何实现一条射线穿过多个方块,并返回排序后的碰撞点列表?

解读

国内 Pygame 岗位面试常把“射线”作为 2D 空间查询的试金石,考察候选人对“向量-矩形相交、参数排序、浮点容差、性能优化”四方面的掌握。
题目隐含三点要求:

  1. 射线有方向,需排除反向交点;
  2. 同一射线可能先后穿过若干 AABB(轴对齐方块),必须按“沿射线距离”升序返回;
  3. 结果要可复用、易调试,最好纯 Python 实现,方便教学与 GameJam 场景。

面试官通常会在白板或 IDE 里让你手写函数,随后追问“如果方块数量 >10k 如何优化”“如何支持旋转矩形”或“如何容差浮点误差”,因此答案必须结构清晰、边界完整、可逐层升级。

知识点

  1. 射线表示:起点 origin、方向向量 dir(可不归一化,但参数 t 需除以 dir.length())。
  2. AABB 相交:Slab 法(分离轴特例)求进入/退出参数 t_min、t_max;若 t_max < t_min 则无交。
  3. 参数过滤:只保留 t_enter ≥ 0 且 t_exit ≥ t_enter 的区段;若 dir 某分量为 0,需单独处理平行且在外部的情况。
  4. 排序键:以 t_enter 升序;若同一方块两面相交,需拆成两个点或只取最近面,视需求而定。
  5. 浮点容差:与 0 比较时用 abs(x) < 1e-6,防止方块共面或射线贴边导致的抖动。
  6. 复杂度:朴素遍历 O(N);若面试追问,可引出“均匀网格、四叉树、扫描线”等加速,但先给出正确性优先的朴素版。
  7. Pygame 生态:利用 pygame.math.Vector2 做向量运算,利用 pygame.Rect 暂存 AABB,但计算时仍用 float,避免 Rect 的 int 截断。

答案

import pygame
from typing import List, Tuple

Ray = pygame.math.Vector2   # 起点
Vec2 = pygame.math.Vector2

def ray_intersect_rects(origin: Vec2, direction: Vec2,
                        rects: List[pygame.Rect]) -> List[Tuple[float, Vec2, pygame.Rect]]:
    """
    返回沿射线升序排列的碰撞信息列表:
    每项为 (t, point, rect)
    t: 沿射线参数,point = origin + t * dir_normalized
    """
    EPS = 1e-6
    dir_norm = direction.normalize() if direction.length_squared() > EPS else Vec2(1, 0)
    inv_dir = Vec2(1.0 / (dir_norm.x or EPS), 1.0 / (dir_norm.y or EPS))
    hits = []

    for r in rects:
        # 将 Rect 看作闭合区间 [left, right] [top, bottom]
        left, top, right, bottom = float(r.left), float(r.top), float(r.right), float(r.bottom)
        # 计算进入/退出两个面的参数
        t_near_x = (left - origin.x) * inv_dir.x
        t_far_x  = (right - origin.x) * inv_dir.x
        t_near_y = (top - origin.y) * inv_dir.y
        t_far_y  = (bottom - origin.y) * inv_dir.y

        # 校正 near <= far
        if t_near_x > t_far_x:
            t_near_x, t_far_x = t_far_x, t_near_x
        if t_near_y > t_far_y:
            t_near_y, t_far_y = t_far_y, t_near_y

        t_enter = max(t_near_x, t_near_y)
        t_exit  = min(t_far_x, t_far_y)

        # 无交
        if t_exit < 0 or t_exit < t_enter - EPS:
            continue
        # 只取射线正向部分
        t_enter = max(t_enter, 0.0)
        point = origin + t_enter * dir_norm
        hits.append((t_enter, point, r))

    # 按 t 升序
    hits.sort(key=lambda x: x[0])
    return hits

使用示例(可直接在 Pygame 主循环里调试):

if __name__ == "__main__":
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    rects = [pygame.Rect(100, 100, 50, 50),
             pygame.Rect(180, 120, 60, 40),
             pygame.Rect(300, 100, 40, 80)]
    origin = Vec2(30, 130)
    direction = Vec2(1, 0.2)

    hits = ray_intersect_rects(origin, direction, rects)
    for t, p, r in hits:
        print(f"t={t:.2f}  point=({p.x:.1f},{p.y:.1f})  rect={r}")

    # 可视化
    screen.fill((30, 30, 30))
    for r in rects:
        pygame.draw.rect(screen, (0, 200, 0), r, 2)
    pygame.draw.circle(screen, (255, 0, 0), origin, 4)
    if hits:
        pygame.draw.line(screen, (255, 255, 0), origin,
                         origin + hits[-1][0] * direction.normalize(), 2)
    pygame.display.flip()
    pygame.time.wait(3000)

该实现满足:

  • 纯 Python,无第三方依赖;
  • 时间复杂度 O(N),空间 O(K)(K 为命中数);
  • 浮点容差、零方向、负方向全部覆盖;
  • 返回列表天然有序,可直接用于“穿墙弹”“激光连锁”等玩法。

拓展思考

  1. 旋转矩形:将射线变换到矩形本地坐标系,或改用分离轴定理(SAT)求入/出参数。
  2. 海量方块:预建均匀网格或四叉树,按格子索引快速剔除,复杂度降至 O(G + N_g)(G 为穿过格子数,N_g 为格内方块数)。
  3. 浮点鲁棒性:采用“整数射线”或“固定点 64bit”避免 1e-6 误差,在像素级关卡中可完全精确。
  4. 回调式迭代:将函数改为生成器,每找到一个交点就 yield,支持“提前停”场景(如视线被第一个墙体挡住)。
  5. 三维迁移:思路完全一致,只需把 Slab 法扩展到 z 轴,即可用于 pygame 的姐妹项目 panda3d 或 Godot 的 2.5D 玩法验证。