A-frame中如何实现GLTF模型持续平滑动画跟随相机位置
实现方案
你需要通过自定义A-frame组件配合多动画配置来实现带平滑过渡的相机跟随效果,同时保留原有模型的上下浮动动画,修改方法如下:
步骤1:补充相机标签并配置多动画
首先给场景添加带id的相机,同时给GLTF模型拆分动画属性:用animation__float保留原有上下浮动效果,新增animation__follow专门处理位置跟随动画。
步骤2:添加平滑跟随自定义组件
注册一个全局自定义组件,实时获取相机位置,动态更新跟随动画的目标位置。
完整可运行代码如下:
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script> <script> AFRAME.registerComponent('smooth-follow', { schema: { offset: {type: 'vec3', default: {x:0, y:2.3, z:-1}}, // 模型相对于相机的固定偏移量 followDur: {type: 'number', default: 200} // 跟随动画时长,数值越小跟随越灵敏 }, tick: function () { const cam = document.querySelector('#playerCam').object3D const targetPos = new THREE.Vector3() // 计算相机坐标系下的偏移目标点 targetPos.copy(this.data.offset) cam.localToWorld(targetPos) // 更新跟随动画的目标位置 this.el.setAttribute('animation__follow', 'to', `${targetPos.x} ${targetPos.y} ${targetPos.z}`) } }) </script> <a-scene> <!-- 新增带id的相机 --> <a-camera id="playerCam" position="0 1.6 0"></a-camera> <!-- 修改后的GLTF模型 --> <a-gltf-model class="cube" mixin="cube" smooth-follow animation__float='property: position.y; dur: 2500; from: 2.3; to: 2.5; dir: alternate; autoplay: true; easing: linear; loop: true;' animation__follow='property: position; dur: 200; easing: easeOutQuad;' src="https://cdn.glitch.com/bb5471f0-16f5-4309-8c7c-52310dc4ff58%2FRobotfr.glb?v=1625527911166" position="0 2.3 -1" scale="1.2 1.2 1.2" speech-command__show="command: assistant; type: attribute; attribute: visible; value: true;" speech-command__hide="command: hide; type: attribute; attribute: visible; value: false;" ></a-gltf-model> </a-scene>
核心说明
- 相对偏移量可以通过修改
smooth-follow组件的offset参数调整,默认保持你原有的相机前1米、高度2.3米的相对位置 - 跟随灵敏度可以通过修改
followDur参数调整,数值越低跟随越跟手,数值越高过渡越平缓 - 两个动画通过后缀
__float和__follow区分,互不干扰,原有浮动效果完全保留
内容的提问来源于stack exchange,提问作者Aidan Young
相关产品推荐
相关产品推荐

