Three.js 曲线路径动画
提示词
使用 Three.js 的 CatmullRomCurve3 创建曲线路径,让模型沿曲线移动,使用 GLTFLoader 加载模型。
效果描述
这是一个使用 Three.js 曲线让模型沿路径移动的示例,展示如何创建曲线路径和沿路径运动。
效果特性
- 曲线路径:使用 CatmullRomCurve3 创建平滑曲线
- 路径可视化:使用 Line 显示曲线路径
- 模型移动:模型沿曲线移动
- 模型朝向:模型朝向路径前方
- GLTF 加载:使用 GLTFLoader 加载模型
- Draco 解码:使用 DRACOLoader 解码压缩模型
核心参数
| 参数 |
值 |
说明 |
| 曲线点数 |
5 |
曲线控制点数量 |
| 路径细分 |
500 |
曲线细分点数 |
| 移动速度 |
0.0004 |
每帧移动进度 |
| 模型路径 |
/files/model/car.glb |
GLTF 模型文件 |
核心代码解析
创建曲线
const curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(20, 15, 0),
new THREE.Vector3(15, 0, 20),
new THREE.Vector3(5, 15, -5),
new THREE.Vector3(10, 0, -10),
]);
可视化曲线
const geometry = new THREE.BufferGeometry().setFromPoints(curve.getPoints(500));
const material = new THREE.LineBasicMaterial({ color: 0xffffff });
const curveMesh = new THREE.Line(geometry, material);
scene.add(curveMesh);
沿曲线移动
let t = 0;
car.render = () => {
t += 0.0004;
const point = curve.getPointAt(t % 1);
car.position.set(point.x, point.y, point.z);
car.lookAt(curve.getPointAt((t + 0.01) % 1));
};
GLTF 模型加载
const loader = new GLTFLoader();
loader.setDRACOLoader(new DRACOLoader().setDecoderPath(FILE_HOST + "libs/threejs/examples/jsm/libs/draco/"));
loader.load(FILE_HOST + "/files/model/car.glb", (gltf) => {
car = gltf.scene;
scene.add(car);
car.render = () => {
t += 0.0004;
const point = curve.getPointAt(t % 1);
car.position.set(point.x, point.y, point.z);
car.lookAt(curve.getPointAt((t + 0.01) % 1));
};
});
技术亮点
- CatmullRomCurve3:创建平滑的 Catmull-Rom 曲线
- 路径细分:getPoints(500) 获取细分点
- 沿路径移动:getPointAt(t) 获取路径上的点
- 模型朝向:lookAt() 让模型朝向路径前方
- Draco 解码:使用 DRACOLoader 解码压缩模型
调试技巧
- 移动速度:调整 t 的增量控制移动速度
- 曲线形状:调整控制点位置改变曲线形状
- 朝向偏移:调整 lookAt 的偏移量控制朝向
- 路径显示:使用 Line 可视化曲线路径
- 循环移动:使用 t % 1 实现循环移动
扩展方向
- 多条路径:创建多条曲线路径
- 速度变化:根据路径位置调整速度
- 路径动画:动画曲线路径本身
- 多模型:多个模型沿不同路径移动
- 路径跟随:相机跟随模型沿路径移动
本文档由 ThreeLab 编辑整理,如需转载,请注明出处。
💬 评论区
评论功能即将上线,敬请期待!