A-Frame实体如何实现公转而非自转,修复mouseenter动画仅触发一次问题
A-Frame动画问题修复方案
需求实现逻辑
两个问题可以通过调整动画绑定对象+配置动态起始点解决:
- 公转效果本质是父实体旋转带动有位置偏移的子实体旋转,因此hover触发的高速动画需要绑定到父实体上,而非子实体自身
- 每次hover都从当前位置触发动画,不需要写死
from值,直接用A-Frame动画组件支持的current关键字即可,会自动读取属性当前值作为动画起始点
完整修改代码
<a-entity class="rota" id="duck1" color="#fdfd96" scale="0.1 0.1 .1" position="2 0 -7" <!-- 原有基础慢公转动画 --> animation="property: rotation; to:0 -360 0; loop:true; easing:linear; dur:30000" <!-- 新增hover触发的高速公转动画 --> animation__hover="property: rotation; from: current; to:0 -720 0; easing:linear; dur:4000; startEvents: fastRotate; autoplay: false" > <a-entity class="rota" color="#F0FFF0" gltf-model="spaceship.glb" position="0 0 1" scale="2 3 3" collison-check="el: #otherduck; radius: 0.15; other-radius: 0.15;" > </a-entity> </a-entity> <!-- hover事件触发逻辑,无需引入额外组件 --> <script> document.querySelector('#duck1 > a-entity').addEventListener('mouseenter', () => { document.querySelector('#duck1').emit('fastRotate') }) </script>
关键配置说明
from: current:每次触发动画时自动读取父实体当前旋转角度作为起始点,无需固定值,完美解决动画仅能触发一次的问题- 动画绑定到父实体:和原有基础公转逻辑一致,父实体旋转时自动带动子实体完成公转效果,调整
animation__hover的dur参数即可调整高速公转的速度 - 如果需要鼠标移出时恢复原有慢公转速度,可新增mouseleave事件监听,暂停高速动画即可:
document.querySelector('#duck1 > a-entity').addEventListener('mouseleave', () => { const parentEl = document.querySelector('#duck1') parentEl.components['animation__hover'].pause() })
内容的提问来源于stack exchange,提问作者Psychonaut007
相关产品推荐
相关产品推荐

