Unity 开源分享一个轻量路点编辑器插件 常用于对象寻路
Unity 食用文档(WaypointPath & Bezier 移动) 源码在最下方
1. 简介
本系统实现了一个可视化路点编辑器,支持:
-
在 Scene 视图中添加、删除、拖动路点
-
路点数据存储在
List<Vector3>
中 -
运行时对象沿路点移动
-
平滑贝塞尔曲线移动
-
移动时自动旋转以跟随方向
适合用于:
-
NPC 巡逻
-
车辆行驶
-
相机轨迹
2. 核心组件
2.1 WaypointPath.cs
-
作用:存储路点数据,并在 Scene 中可视化
-
字段
字段 | 类型 | 说明 |
---|---|---|
m_Points | List<Vector3> | 路点列表(本地空间坐标) |
m_Closed | bool | 是否闭合路径 |
m_LineColor | Color | Gizmos 线颜色 |
m_SelectedColor | Color | 当前选中点颜色 |
m_PointSize | float | 路点球体大小 |
m_ShowIndices | bool | 显示索引标签 |
m_SelectedIndex | int | 当前选中路点(编辑器用) |
-
功能
-
在 Scene 中显示路点球体
-
通过 Inspector 或 Scene 操作增删点
-
支持闭合路径显示
-
-
示例 Gizmos 代码(编辑器显示点与索引):
private void OnDrawGizmos() { Gizmos.matrix = transform.localToWorldMatrix; for (int i = 0; i < m_Points.Count; i++) { Gizmos.color = (i == m_SelectedIndex) ? m_SelectedColor : m_LineColor; Gizmos.DrawSphere(m_Points[i], m_PointSize); } }
2.2 WaypointPathEditor.cs
-
作用:自定义 Inspector 和 Scene 交互
-
功能
-
ReorderableList 显示路点
-
Inspector 上支持:
-
添加 / 删除 / 插入路点
-
闭合路径设置
-
曲线平移 / 归中 / 等间距重采样(可选)
-
-
Scene 视图操作:
-
Shift + 左键:添加路点
-
点击球体:选中路点
-
拖动手柄:移动路点
-
Delete / Backspace:删除选中点
-
-
2.3 WaypointMoverBezier.cs
-
作用:运行时沿路点移动,并平滑旋转跟随方向
-
字段
字段 | 类型 | 说明 |
---|---|---|
m_Path | WaypointPath | 路点引用 |
m_Speed | float | 移动速度 |
m_Loop | bool | 循环播放 |
m_PingPong | bool | 来回播放 |
m_CurrentIndex | int | 当前起始点索引 |
m_Direction | int | 来回模式方向 |
m_T | float | 曲线进度 [0,1] |
-
移动方式
-
使用 Catmull-Rom 样条插值点
-
m_T
记录曲线段进度 -
到达下一个点后切换索引
-
-
旋转方式
-
计算切线方向:
Vector3 dir = (CatmullRom(P0, P1, P2, P3, t + 0.01f) - pos).normalized; transform.rotation = Quaternion.LookRotation(dir, Vector3.up);
-
-
Scene 视图可视化
-
绘制 Catmull-Rom 样条曲线
-
当前移动对象 → 下一个目标点线段
-
3. 使用方法
3.1 路点编辑
-
创建空对象,挂上
WaypointPath
。 -
在 Inspector 添加几个路点,或在 Scene:
-
Shift + 左键点击地面添加
-
左键点击球体选择,拖动调整
-
Delete 删除选中点
-
-
可选:
-
勾选
Closed
让路径闭合 -
调整
m_LineColor
/m_SelectedColor
/m_PointSize
-
3.2 运行时移动
-
找一个对象(Cube 或 NPC),挂上
WaypointMoverBezier
。