如何让A-frame中的立方体旋转到随机角度并按1秒间隔循环执行
实现方案
你只需要移除原有animation的固定循环逻辑,新增自定义逻辑监听动画结束事件、动态生成随机角度更新动画参数即可,完整修改后的代码如下:
<html> <head> <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script> <script> // 注册自定义随机旋转组件 AFRAME.registerComponent('random-rotate', { init: function () { const rotateEl = this.el; // 监听动画结束事件 rotateEl.addEventListener('animationcomplete', () => { // 旋转结束后延迟1秒执行下一次 setTimeout(() => { // 生成0~360区间的随机角度 const randX = Math.floor(Math.random() * 360); const randY = Math.floor(Math.random() * 360); const randZ = Math.floor(Math.random() * 360); // 更新动画目标角度 rotateEl.setAttribute('animation', 'to', `${randX} ${randY} ${randZ}`); // 启动下一次动画 rotateEl.components.animation.begin(); }, 1000); }); } }); </script> </head> <body> <a-scene> <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box> <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere> <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder> <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane> <!-- 新增random-rotate组件,移除原有loop配置 --> <a-entity random-rotate animation="property: rotation; to: 20 0 0; delay: 1000; dur: 1000" > <a-box position="5 0 0" color="mediumseagreen"></a-box> </a-entity> <a-sky color="#ECECEC"></a-sky> </a-scene> </body> </html>
修改说明
- 移除了原有
animation属性中的loop: true配置,固定循环逻辑无法实现随机角度更新,改为手动控制动画触发 - 新增自定义
random-rotate组件,核心逻辑为:- 监听A-frame原生的
animationcomplete动画结束事件 - 每次动画结束后等待1秒,生成x、y、z三轴0~360区间的随机角度
- 更新动画组件的目标角度参数,主动触发下一次旋转
- 监听A-frame原生的
- 保留了你原有配置的1000ms旋转时长、首次启动前1000ms延迟的逻辑,和需求要求的旋转后间隔1秒执行下一次的逻辑完全匹配
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

