Search code examples
animationaframe

How do you make multiple animations start from clicking one object?


I've started learning a-frame recently and I'm trying to create a domino effect type thing. I want all of my animations to start after I click on the first object. I've tried using delay but the delay starts immediately instead of after I start the animation. How do I make it so after someone clicks object 1, object 2's animation would start shortly after?


Solution

  • Let's try the delay approach - with a custom component for some managment :)


    Lets say you have a setup like this (html pseudocode):

    <a-box class='domino' foo animation='startEvents: go; ...
    <a-box class='domino' animation='startEvents: go; delay: 200 ...
    <a-box class='domino' animation='startEvents: go; delay: 400 ...
    

    All items have some attributes / components:

    • The class attribute to make them easy to both grab and distinguish from any other entities.
    • The animation component which will make them animate - whats important: startEvents - here we'll throw the event which will be emitted simultaneously on all boxes, delay - so every next box will wait before moving.
    • This foo component - we'll make it by ourselves. It will detect a mouseclick, and emit the go event on all boxes.

    So the concept is as follows:

    1. We click one box with the foo component
    2. the foo component detects the click and emits go on all .domino elements
    3. all .domino elements should start their animations one after another - but each one 200ms later than the previous one.

    Now lets make the custom component. Keep in mind it has to be defined before the <a-scene>:

    <script src='component.js'></script>
    <script>
       // component
    </script>
    
    <a-scene>
    </a-scene>
    

    We will implement all logic within the init function - which is called upon initialisation.

    // component definition 
    AFRAME.registerComponent('foo', {
    
      // this is called upon initialisation
      init: function() {
    
         // grab all the domino pieces
         var pieces = document.getElementsByClassName('domino')
    
         // if this one gets pressed...
         this.el.addEventListener('click', e => {
    
           // ...emit the event on all of them
           for (let piece of pieces) {
             piece.emit('go')
           }
         })
       }
    })
    

    and actually - thats it. To see it in action - here are two examples - in both clicking the blue box, should start the animation.

    1. Simple delayed animation cascade
    2. Domino-like animation