跳转到内容

空间索引系统 (Spatial)

@esengine/spatial 提供了高效的空间查询和索引功能,包括范围查询、最近邻查询、射线检测和 AOI(兴趣区域)管理。

Terminal window
npm install @esengine/spatial
import { createGridSpatialIndex } from '@esengine/spatial';
// 创建空间索引(网格单元格大小为 100)
const spatialIndex = createGridSpatialIndex<Entity>(100);
// 插入对象
spatialIndex.insert(player, { x: 100, y: 200 });
spatialIndex.insert(enemy1, { x: 150, y: 250 });
spatialIndex.insert(enemy2, { x: 500, y: 600 });
// 查找半径内的对象
const nearby = spatialIndex.findInRadius({ x: 100, y: 200 }, 100);
console.log(nearby); // [player, enemy1]
// 查找最近的对象
const nearest = spatialIndex.findNearest({ x: 100, y: 200 });
console.log(nearest); // enemy1
// 更新位置
spatialIndex.update(player, { x: 120, y: 220 });
import { createGridAOI } from '@esengine/spatial';
// 创建 AOI 管理器
const aoi = createGridAOI<Entity>(100);
// 添加观察者(玩家)
aoi.addObserver(player, { x: 100, y: 100 }, { viewRange: 200 });
aoi.addObserver(npc, { x: 150, y: 150 }, { viewRange: 150 });
// 监听进入/离开事件
aoi.addListener((event) => {
if (event.type === 'enter') {
console.log(`${event.observer} 看到了 ${event.target}`);
} else if (event.type === 'exit') {
console.log(`${event.target} 离开了 ${event.observer} 的视野`);
}
});
// 更新位置(会自动触发进入/离开事件)
aoi.updatePosition(player, { x: 200, y: 200 });
// 获取视野内的实体
const visible = aoi.getEntitiesInView(player);
特性空间索引 (SpatialIndex)AOI (Area of Interest)
用途通用空间查询实体可见性追踪
事件无事件通知进入/离开事件
方向单向查询双向追踪(谁看到谁)
场景碰撞检测、范围攻击MMO 同步、NPC AI 感知
interface IBounds {
readonly minX: number;
readonly minY: number;
readonly maxX: number;
readonly maxY: number;
}
interface IRaycastHit<T> {
readonly target: T; // 命中的对象
readonly point: IVector2; // 命中点坐标
readonly normal: IVector2; // 命中点法线
readonly distance: number; // 距离射线起点的距离
}