AFrame中同一实体标签内两个动画切换时的位置如何同步?
问题原因
你遇到的现象是AFrame动画组件的默认机制导致的:动画暂停时会记录当前的播放进度,调用resume恢复时会直接从该进度继续播放,不会读取实体当前的实际属性值作为新的播放起点。
另外你的代码存在一个冗余问题:把animationcomplete监听写在了tick函数里,tick每帧都会执行,会重复绑定成百上千次相同的监听,导致后续回调逻辑被多次触发。
修复方案
不用自带的resumeEvents机制,在hover动画播放完成后,手动读取实体当前的实时角度,重置默认动画的起止参数后重新启动动画即可,修改后的完整代码如下:
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script> <script> AFRAME.registerComponent('eventhandling', { init: function () { const el = this.el; // 仅监听hover动画的完成事件,避免其他动画结束触发回调 el.addEventListener('animationcomplete__mouseenter', function() { // 读取实体当前的实时旋转角度 const currentRot = el.getAttribute('rotation'); // 重置默认动画的起止点,保证从当前角度继续按原方向旋转 el.setAttribute('animation', { from: `${currentRot.x} ${currentRot.y} ${currentRot.z}`, to: `${currentRot.x} ${currentRot.y - 360} ${currentRot.z}` }); // 重新启动默认动画,代替原有的resume逻辑 el.components.animation.beginAnimation(); }); } }); </script> </head> <body> <a-scene> <a-entity class="rota" id="duck1" color="#FF0000" scale="0.1 0.1 .1" position="2 0 -7" animation="property: rotation; from: 0 0 0; to:0 -360 0; loop:true; easing:linear; dur:30000; pauseEvents: mouseenter" animation__mouseenter="property: rotation; to:0 360 0; easing:linear; dur:4000; startEvents: mouseenter" eventhandling> <a-box class="rota" color="#FF0000" gltf-model="spaceship.glb" position="20 0 -10" scale="2 3 3" collison-check="el: #otherduck; radius: 0.15; other-radius: 0.15;"> </a-box> </a-entity> <a-camera position="0 1.2 1.3"><a-cursor objects=".rota" ></a-cursor></a-camera> </a-scene> </body> </html>
逻辑说明
- 移除了原有动画配置里多余的
resumeEvents、pauseEvents参数,避免和手动逻辑冲突 - 将事件监听移到
init生命周期里,仅绑定一次回调 - hover动画播放完成后,先获取实体当前的实际旋转值,用这个值作为默认动画的新起点,重新计算终点后启动动画,就会从当前位置无缝衔接继续旋转
内容的提问来源于stack exchange,提问作者Psychonaut007
相关产品推荐
相关产品推荐

