Code2025

碰撞检测与跳跃手感:命中盒为什么要故意缩小,重力为什么不对称

写于 2026-11-16·更新于 2026-11-16·4701 字·6 段可运行·5 条反链
本页目录

个人小程序合集:从恐龙快跑的两个版本,看一个项目是怎么长大的10 里记过一个 v1 的死代码 bug:「按住空格跳更高」那段逻辑从来没生效过——max(velocity, -jump_speed) 永远返回 velocity 自己。笔记结尾我写了正确的修法:「应该在按住时抵消部分重力」。

这一篇就是那个修法的真实实现。 恐龙快跑的第三次重写(3152 行 JS 小游戏版)里,可变重力真的写对了:

javascript
const grav = (this.dino.vy < 0 && this.jumpHeld) ? 0.18 : 0.42;
this.dino.vy += grav;
if (this.dino.vy > 16) this.dino.vy = 16;
this.dino.y += this.dino.vy;

上升且按住 → 重力 0.18;松开或下落 → 0.42。下落重力是上升的 2.3 倍。这不是物理,这是手感设计。下面把这套代码里四个和"手感"有关的机制拆开,每个都用 Python 实跑验证。

对应的移植代码在 代码/15·练手项目/个人小程序合集/恐龙快跑小游戏版/碰撞检测_py移植.py 和 难度曲线_py移植.py。

一、AABB:判"不相交"比判"相交"简单#

轴对齐包围盒(Axis-Aligned Bounding Box)就是"不与坐标轴成角度的矩形"。两个矩形相交的判定:

python
def aabb(a, b):    """a/b 都是 {"x","y","w","h"},x/y 是左上角"""    return (a["x"] < b["x"] + b["w"] and a["x"] + a["w"] > b["x"]            and a["y"] < b["y"] + b["h"] and a["y"] + a["h"] > b["y"])  base = {"x": 100, "y": 100, "w": 50, "h": 50}cases = [    ("完全分离(右)", {"x": 200, "y": 100, "w": 30, "h": 30}),    ("部分重叠",       {"x": 130, "y": 130, "w": 30, "h": 30}),    ("完全包含",       {"x": 110, "y": 110, "w": 10, "h": 10}),    ("恰好贴边",       {"x": 150, "y": 100, "w": 30, "h": 30}),]for name, b in cases:    print("  {:<14} 相交 = {}".format(name, aabb(base, b)))

直接判"相交"要分四种情况(左压右、右压左、上压下、下压上),写起来啰嗦还容易漏。反过来判"不相交"只要四条:

text
a 完全在 b 左边  →  a.x + a.w <= b.x
a 完全在 b 右边  →  a.x >= b.x + b.w
a 完全在 b 上边  →  a.y + a.h <= b.y
a 完全在 b 下边  →  a.y >= b.y + b.h

四条都不成立 = 相交。所以代码写成"分离条件全部取反再 and 起来"。

pygame 那边等价的是 rect.colliderect(),一行搞定,但代价是你看不到这四条——见 pygame 游戏循环的两种写法:贪吃蛇的列表蛇身与吃豆人的路径表7。

二、命中盒内缩:让"看着没碰到"就真的不算碰到#

这是全篇最反直觉的一条。恐龙精灵是 130×155,但它的碰撞盒只有 50×105:

javascript
// game.js:1421
const dinoBox = { x: this.dino.x + 40, y: this.dino.y + 30,
                  w: this.dino.w - 80, h: this.dino.h - 50 };
// game.js:1425
const oBox = { x: o.x + 8, y: o.y + 4, w: o.w - 16, h: o.h - 8 };
python
def aabb(a, b):    return (a["x"] < b["x"] + b["w"] and a["x"] + a["w"] > b["x"]            and a["y"] < b["y"] + b["h"] and a["y"] + a["h"] > b["y"])  dino = {"x": 100, "y": 600, "w": 130, "h": 155}   # 恐龙精灵原尺寸obs = {"x": 190, "y": 700, "w": 60, "h": 60}      # 一个障碍物 print("按精灵原尺寸判定:", aabb(dino, obs), "← 玩家会觉得冤") dino_box = {"x": dino["x"] + 40, "y": dino["y"] + 30,            "w": dino["w"] - 80, "h": dino["h"] - 50}obs_box = {"x": obs["x"] + 8, "y": obs["y"] + 4,           "w": obs["w"] - 16, "h": obs["h"] - 8}print("按内缩命中盒判定:", aabb(dino_box, obs_box), "← 游戏实际用的")print()print("恐龙盒 {}×{} → {}×{}".format(    dino["w"], dino["h"], dino_box["w"], dino_box["h"]))print("面积从 {} 缩到 {},只剩 {:.0%}".format(    dino["w"] * dino["h"], dino_box["w"] * dino_box["h"],    dino_box["w"] * dino_box["h"] / (dino["w"] * dino["h"])))

碰撞盒只剩精灵面积的 26%,等于给玩家放掉了四分之三的"命中面积"。

为什么这么狠?因为精灵图里的尾巴、头冠、脚爪、翅膀尖都是视觉装饰。玩家看的是"恐龙的身体有没有撞上刺猬",而程序看的是"两个矩形有没有重叠"。这两个判断天然不一致——按整张图判,玩家会频繁遇到"我明明躲过去了却死了"。

这是动作游戏最招骂的手感问题,术语叫 unfair hit。解法就是命中盒(hitbox)内缩,宁可判松不可判严。两边都内缩(恐龙缩 40/30,障碍物缩 8/4)等于双重容错。

三、四角采样 + 分轴移动:瓦片地图的两招#

迷宫模式(NoviceMode)不能用 AABB 了,因为墙不是一個矩形,是一整张网格。

四角采样#

javascript
// game.js:1559
canMoveTo(nx, ny) {
  const d = this.dino;
  const corners = [
    [nx + 2, ny + 2], [nx + d.w - 2, ny + 2],
    [nx + 2, ny + d.h - 2], [nx + d.w - 2, ny + d.h - 2]
  ];
  for (const [px, py] of corners) {
    const gx = Math.floor((px - MAZE_OX) / CELL);
    const gy = Math.floor((py - MAZE_OY) / CELL);
    if (gx < 0 || gx >= MAZE_COLS || gy < 0 || gy >= MAZE_ROWS) return false;
    if (this.grid[gy][gx] === 1) return false;
  }
  return true;
}

只检查四个角,不检查整块面积。 为什么够:瓦片地图里墙是整格的(CELL = 46),角色比格子小(30×30),所以只要四个角都不在墙里,中间就不可能在墙里。每帧每角色只要 4 次数组查表,比遍历覆盖的所有格子快得多。

内缩 2px 是给角色留的贴墙余量,避免浮点误差把它卡在墙缝里抖动。

分轴移动#

javascript
// game.js:1588
if (dx !== 0 && this.canMoveTo(d.x + dx, d.y)) d.x += dx;
if (dy !== 0 && this.canMoveTo(d.x, d.y + dy)) d.y += dy;

这两行看着平平无奇,是整份代码里最值得学的一招。注意第二个判定用的是已经更新过的 d.x。

python
CELL = 46  def can_move_to(grid, nx, ny, w, h, cols, rows):    corners = [(nx + 2, ny + 2), (nx + w - 2, ny + 2),               (nx + 2, ny + h - 2), (nx + w - 2, ny + h - 2)]    for px, py in corners:        gx, gy = int(px // CELL), int(py // CELL)        if not (0 <= gx < cols and 0 <= gy < rows):            return False        if grid[gy][gx] == 1:            return False    return True  def move_axis_separated(grid, x, y, dx, dy, w, h, cols, rows):    if dx != 0 and can_move_to(grid, x + dx, y, w, h, cols, rows):        x += dx    if dy != 0 and can_move_to(grid, x, y + dy, w, h, cols, rows):        y += dy    return x, y  grid = [    [0, 0, 0, 0, 0, 0],    [0, 1, 1, 1, 1, 0],    [0, 1, 0, 0, 1, 0],    [0, 1, 0, 0, 1, 0],    [0, 1, 1, 1, 1, 0],    [0, 0, 0, 0, 0, 0],]COLS = ROWS = 6print("网格(█=墙,·=可走):")for r in grid:    print("  " + "".join("█" if c else "·" for c in r)) w, h = 30, 30x, y = 150, 100          # 站在房间里、靠右墙print()print("角色:像素 ({},{}),尺寸 {}×{},覆盖 col {}~{}".format(    x, y, w, h, x // CELL, (x + w - 1) // CELL))print("向右走  4px → {}  (右边缘 {} 仍在 col 3)".format(    can_move_to(grid, x + 4, y, w, h, COLS, ROWS), x + 4 + w - 2))print("向右走 20px → {}  (右边缘 {} 落进 col 4 = 墙)".format(    can_move_to(grid, x + 20, y, w, h, COLS, ROWS), x + 20 + w - 2)) dx, dy = 20, 20both = can_move_to(grid, x + dx, y + dy, w, h, COLS, ROWS)nx, ny = move_axis_separated(grid, x, y, dx, dy, w, h, COLS, ROWS)print()print("贴着右墙斜向移动 (dx=20, dy=20):")print("  整体判定(一次判两轴):{}  ← 直接拒绝,角色卡死在墙角".format(both))print("  分轴判定(先横后竖)  :({},{}) → ({},{})".format(x, y, nx, ny))print("  → 横向被墙挡住(x 没变),纵向照常走(y 前进了 {}px)".format(ny - y))

如果直接判 canMoveTo(x+dx, y+dy),斜着走向墙角时会被整体拒绝,角色就在墙角前完全卡死——明明贴着墙还能滑,手感却像撞上一堵看不见的空气墙。

分开判之后:横向被挡只挡横向,纵向照常走,角色贴着墙滑过去。这正是玩家期望的行为,所有 2D 动作游戏都这么做。

那个网格是哪来的#

this.grid 就是 种子随机与迷宫生成:mulberry32、递归回溯,以及那 120 步保底走廊7 生成的二维数组,1 是墙 0 是路。像素坐标转网格坐标只有一步:Math.floor((px - MAZE_OX) / CELL)——减去迷宫原点偏移,除以格子边长,向下取整。

这个"二维数组表示网格"的思路和 扫雷:二维数组怎么表示九宫格,以及为什么第一下点击有 20% 概率直接去世4 完全一样,那边是九宫格数雷,这边是四角查墙。

四、可变重力:跳跃手感的来源#

回到开头那三行。把它跑出来看:

python
GROUND_Y, DINO_H = 820, 155IMPULSE = -15.5          # 起跳冲量(负 = 向上)G_HOLD, G_FALL = 0.18, 0.42TERMINAL = 16  def jump(held):    """模拟一次跳跃:按住 held 帧后松手,返回 (最大高度, 滞空帧数)"""    y = GROUND_Y - DINO_H    vy = IMPULSE    top, frames = y, 0    while True:        frames += 1        # 上升中(vy<0)且还按着 → 小重力;否则 → 大重力        vy += G_HOLD if (vy < 0 and frames <= held) else G_FALL        vy = min(vy, TERMINAL)          # 钳住终端速度        y += vy        top = min(top, y)        if y >= GROUND_Y - DINO_H:            break        if frames > 600:            break    return GROUND_Y - DINO_H - top, frames  print("{:>10} {:>12} {:>12}".format("按住帧数", "最大高度", "滞空帧数"))for held in (0, 5, 10, 20, 40, 999):    h, f = jump(held)    print("{:>10} {:>12.1f} {:>12}".format("全程" if held == 999 else held, h, f)) sym = IMPULSE ** 2 / (2 * G_FALL)var = IMPULSE ** 2 / (2 * G_HOLD)print()print("对称重力(全程 0.42)理论最高 = {:.1f}px".format(sym))print("可变重力(上升 0.18)理论最高 = {:.1f}px".format(var))print("倍率 = {:.2f}×".format(var / sym))

按住时长从 0 帧到全程,跳跃高度从 278px 一路涨到 660px——2.4 倍的可控范围。这就是"轻点跳一下、长按跳很高"的全部实现,三行代码。

对比 v1 那个死代码 bug,正确的修法一目了然:

v1(死代码) 小游戏版(生效)
写法 velocity = max(velocity, -jump_speed) grav = 0.18 if 按住 else 0.42
作用点 夹住速度的下限 改变加速度
实际效果 无(永远返回自己) 上升段变慢 → 跳得更高

v1 想的是"限制速度别变小",但起跳后 velocity += gravity 只会让速度朝 0 靠,max 根本夹不住。正确的思路是改加速度而不是改速度——按住时给个小重力,速度自然衰减得慢,滞空就久。

五、阻尼弹簧:落地那下"啪"的挤压#

恐龙落地时会压扁再弹回,这是个阻尼谐振:

javascript
// game.js:1407
this.dino.squashVel += -this.dino.squash * 0.18 - this.dino.squashVel * 0.80;
this.dino.squash += this.dino.squashVel;
python
def spring(damping, n=20):    squash, vel, out = 0.0, 0.08, []    for _ in range(n):        vel += -squash * 0.18 - vel * damping        squash += vel        if abs(squash) < 0.001 and abs(vel) < 0.001:            squash = vel = 0        out.append(round(squash, 4))        if squash == 0 and vel == 0:            break    return out  real = spring(0.80)print("原版阻尼 0.80:", real)print("→ 单调回 0、不振荡,{} 帧收敛".format(len(real)))print()soft = spring(0.05)print("若改成 0.05:", soft[:14], "...")print("→ 正负来回振荡,恐龙会像果冻一样晃个不停")

两项拆开看:

  • -squash * 0.18 → 回复力,把形变拉回 0(弹簧刚度)
  • -squashVel * 0.80 → 阻尼力,每帧吃掉 80% 的速度

阻尼高达 0.80 意味着这是过阻尼系统:不会来回振荡,形变在 13 帧内单调回弹到 0。恐龙落地"啪"地压扁再弹回,而不是像果冻一样晃个不停。改小到 0.05 就变成欠阻尼,正负来回摆——上面第二组数据就是。

六、难度曲线:两个魔数与一个必须的钳制#

javascript
// game.js:1378
this.speed = this.baseSpeed + this.frame * 0.0008;
// game.js:1416
this.spawnTimer = Math.max(55, 100 - this.frame * 0.008);
python
print("{:>7} {:>7} {:>9} {:>11} {:>11}".format(    "帧", "秒", "速度", "刷怪间隔", "间隔(秒)"))for fr in (0, 600, 1800, 3600, 5625, 9000, 18000):    sp = 4.0 + fr * 0.0008    iv = max(55, 100 - fr * 0.008)    print("{:>7} {:>7.1f} {:>9.2f} {:>11.1f} {:>11.2f}".format(        fr, fr / 60, sp, iv, iv / 60)) print()zero = 100 / 0.008print("若不钳制:frame = {:.0f} 时间隔归零,之后变负".format(zero))

三个数字各自的含义:

魔数 含义 换算
0.0008 每帧增加的速度 60fps 下每秒 +0.048,约 21 秒后速度翻倍(4→8)
55 刷怪间隔下限 ≈ 0.92 秒,玩家能连续跳跃反应的极限
12500 不钳制时间隔归零的帧 ≈ 3.5 分钟

max(55, ...) 这个钳制不是可选的。没有它,frame 到 12500 之后间隔变负数,spawnTimer 永远 <= 0,于是每帧刷一个障碍物,屏幕瞬间糊满。

而且这个 bug 只在玩得足够久(3.5 分钟以上)之后才出现——正好是玩家最投入的时候。

连出去#

附:本单元文件清单#

类型笔记
状态已完成
掌握度
标签#碰撞检测#AABB#游戏手感#物理模拟#瓦片地图#JS移植
创建2026-11-16
更新2026-11-16
源码代码/15·练手项目/个人小程序合集/恐龙快跑小游戏版
可运行是