2.1 像素射线与命中测试
点选是编辑器最频繁的操作:鼠标落点即世界射线,射线与世界几何求交得候选,最近的候选被选中。本节把这条链拆成三个纯函数:反投影、求交、选最近。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 视口相机 | 1.1 相机控制与导航 | 相机把世界变屏幕;本节把屏幕变回射线 |
| 最小视口拾取 | helio 子系统与工具 | 骨架有单条拾取射线;本节做求交库与最近命中 |
| 全卷脉络 | 本卷目录 | toc 列章节;本节是拾取与选择章的地基 |
从零实现:像素射线与命中测试
screenRay 用相机的宽高比与 fov 反投影:近平面上的点就是射线原点方向,取 origin 为相机位置、dir 指向该点。raySphere 解一元二次方程,rayAABB 用 slab 算法解区间交,两者都只取 t>0 的最近交点。pickNearest 对候选数组按 t 排序取最小。
对标编辑器拾取接口
Unity 的 HandleUtility 分别提供 GUI 坐标转世界射线和编辑器对象拾取。helio 示例用相机参数构造射线,与球体和轴对齐包围盒求交。包围盒命中只说明进入了候选范围,精确网格命中需要进一步求交。 Unity HandleUtility
可运行产物:6 条用例
下面是 src/ray-picking.ts,层级 L1,完整可编译。运行命令 node --test test/02-1-pixel-ray-hitting.test.ts:
// file: src/ray-picking.ts
// tier: L1
// verify: node --test test/02-1-pixel-ray-hitting.test.ts
//
// 视图(第二章):拾取与选择——像素到世界射线与命中。
// 编辑器点击视口时,先由屏幕坐标生成一条世界空间射线,再与场景中的
// 包围体求交:球体用解析解、AABB 用 slab 法。命中最近的物体即为拾取
// 结果。这是一切选择、拖拽、gizmo 操作的起点。
import { vec3, add, sub, scale, dot, cross, normalize, length } from './camera-control.ts';
import type { Vec3, Camera } from './camera-control.ts';
export interface Ray {
origin: Vec3;
direction: Vec3;
}
/** 由相机与归一化设备坐标(ndc 的 x/y ∈ [-1,1])生成世界射线。 */
export function screenRay(cam: Camera, ndcX: number, ndcY: number, aspect: number): Ray {
const forward = normalize(sub(cam.target, cam.position));
const right = normalize(cross(forward, cam.up));
const up = normalize(cross(right, forward));
const tanHalf = Math.tan((cam.fov * Math.PI) / 180 / 2);
const dir = normalize(
add(
add(forward, scale(right, ndcX * aspect * tanHalf)),
scale(up, ndcY * tanHalf),
),
);
return { origin: { ...cam.position }, direction: dir };
}
/** 射线与球求交,返回最近正交点参数 t;不相交返回 null。 */
export function raySphere(ray: Ray, center: Vec3, radius: number): number | null {
const oc = sub(ray.origin, center);
const b = dot(oc, ray.direction);
const c = dot(oc, oc) - radius * radius;
const disc = b * b - c;
if (disc < 0) return null;
const sq = Math.sqrt(disc);
const t0 = -b - sq;
const t1 = -b + sq;
if (t0 >= 0) return t0;
if (t1 >= 0) return t1;
return null;
}
/** 射线与 AABB 求交(slab 法),返回最近正交点参数 t;不相交返回 null。 */
export function rayAABB(ray: Ray, min: Vec3, max: Vec3): number | null {
let tmin = -Infinity;
let tmax = Infinity;
const axes: Array<[keyof Vec3, keyof Vec3]> = [
['x', 'x'],
['y', 'y'],
['z', 'z'],
];
for (const [d] of axes) {
const o = ray.origin[d];
const dir = ray.direction[d];
if (Math.abs(dir) < 1e-12) {
if (o < min[d] || o > max[d]) return null;
continue;
}
let t1 = (min[d] - o) / dir;
let t2 = (max[d] - o) / dir;
if (t1 > t2) [t1, t2] = [t2, t1];
tmin = Math.max(tmin, t1);
tmax = Math.min(tmax, t2);
if (tmin > tmax) return null;
}
if (tmax < 0) return null;
return tmin >= 0 ? tmin : tmax;
}
/** 拾取最近的球形包围体,返回其 id;无命中返回 null。 */
export function pickNearest(
ray: Ray,
objects: Array<{ id: string; center: Vec3; radius: number }>,
): string | null {
let best: string | null = null;
let bestT = Infinity;
for (const obj of objects) {
const t = raySphere(ray, obj.center, obj.radius);
if (t !== null && t < bestT) {
bestT = t;
best = obj.id;
}
}
return best;
}
/** 射线在参数 t 处的世界点。 */
export function pointAt(ray: Ray, t: number): Vec3 {
return add(ray.origin, scale(ray.direction, t));
}
/** 射线长度单位化检查(调试辅助)。 */
export function isUnit(ray: Ray): boolean {
return Math.abs(length(ray.direction) - 1) < 1e-9;
}
slab 算法把 AABB 求交变成三次区间交,ray 与包围盒的六个面各给一个区间,区间并集非空即命中,取进入区间的下界为 t。pointAt 是本节的校验器:命中点回投到射线上必须能复现原射线位置,用于测试里的自洽断言。
下面是 test/02-1-pixel-ray-hitting.test.ts,层级 L1:
// file: test/02-1-pixel-ray-hitting.test.ts
// tier: L1
// verify: node --test test/02-1-pixel-ray-hitting.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
screenRay,
raySphere,
rayAABB,
pickNearest,
pointAt,
isUnit,
} from '../src/ray-picking.ts';
import { vec3, makeCamera } from '../src/camera-control.ts';
test('屏幕中心射线沿相机朝向且单位化', () => {
const cam = makeCamera(vec3(0, 0, 10), vec3(0, 0, 0));
const ray = screenRay(cam, 0, 0, 1);
assert.ok(Math.abs(ray.direction.x) < 1e-9);
assert.ok(Math.abs(ray.direction.y) < 1e-9);
assert.ok(Math.abs(ray.direction.z - -1) < 1e-9);
assert.equal(isUnit(ray), true);
});
test('射线-球:正前方球命中且 t 精确', () => {
const ray = { origin: vec3(0, 0, 10), direction: vec3(0, 0, -1) };
const t = raySphere(ray, vec3(0, 0, 0), 1);
assert.equal(t, 9);
});
test('射线-球:偏离的球不命中', () => {
const ray = { origin: vec3(0, 0, 10), direction: vec3(0, 0, -1) };
assert.equal(raySphere(ray, vec3(5, 0, 0), 1), null);
});
test('射线-AABB:正前方盒命中,背面盒返回 null', () => {
const ray = { origin: vec3(0, 0, 10), direction: vec3(0, 0, -1) };
assert.equal(rayAABB(ray, vec3(-1, -1, -1), vec3(1, 1, 1)), 9);
const away = { origin: vec3(0, 0, 10), direction: vec3(0, 0, 1) };
assert.equal(rayAABB(away, vec3(-1, -1, -1), vec3(1, 1, 1)), null);
});
test('pickNearest 返回最近命中物体', () => {
const ray = { origin: vec3(0, 0, 10), direction: vec3(0, 0, -1) };
const objects = [
{ id: 'far', center: vec3(0, 0, 0), radius: 1 },
{ id: 'near', center: vec3(0, 0, 5), radius: 1 },
];
assert.equal(pickNearest(ray, objects), 'near');
assert.equal(pickNearest(ray, []), null);
});
test('pointAt 沿射线取点', () => {
const ray = { origin: vec3(1, 2, 3), direction: vec3(0, 0, -1) };
assert.deepEqual(pointAt(ray, 2), vec3(1, 2, 1));
});
本机实测(Node v26.5.0,node --test test/02-1-pixel-ray-hitting.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。
第一条钉反投影方向(屏幕中心等于相机朝向)。第二、三条钉球体命中的内外与最近点。第四条钉 AABB 命中与正反面。第五条钉最近命中取 t 最小。第六条钉 isUnit 向量数学。
小结
- 屏幕坐标经反投影回到世界射线,链接视口与世界。
- 球体与 AABB 的解析求交给出生动且可断言的命中点。
pickNearest把多个候选收敛为一次选择。- 拾取是选择、高亮、Gizmo 的共同入口,本节把入口的数学写死。
阅读导航:上一节:相机序列与视图书签 · 下一节:ID 缓冲与 GPU 拾取 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。