2
votes

I am creating a scene using A-frame (https://aframe.io) and I'm wondering how I can animate a box to move randomly throughout a certain area. I want to use the animation property (https://aframe.io/docs/1.2.0/components/animation.html#sidebar) to move an entity randomly with a duration of three seconds anywhere from 0 0 0 as starting coordinates to 10 10 10 as boundary coordinates. This means that forever as long as the code is running, the box should animate to a random position from 0 0 0 to 10 10 10 as coordinates and the animation should have a duration of three seconds. How can this be done? Start code:

 <head>
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene>
<a-entity class="move">
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
   </a-entity>
<a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
      <a-sky color="#ECECEC"></a-sky>
    </a-scene>
  </body>
</html>
1

1 Answers

1
votes

Initiate a function when the entity initially loads and at every animationcomplete[https://aframe.io/docs/1.2.0/components/animation.html#api3_animationcomplete] event

<a-box onloaded="rndAnim" onanimationcomplete="rndAnim"></a-box>

The function will set Math.random() * 10 for every coordinate, which will give you a random number until 9.99, then will setAttribute - animation on the element with the new random coordinates within your specified area

function rndAnim(e) {
  let x = Math.random() * 10;
  let y = Math.random() * 10;
  let z = Math.random() * 10;
  e.target.setAttribute('animation', `property: position; from: 0 0 0; to: ${x} ${y} ${z}; dur: 3000; `
}