Search code examples
javascriptaframewebvr

Rewind an animation in A-Frame


I have an a-video somewhere in my scene. When I click a + button next to it, it triggers an animation to scale it up. It also makes visible a - button in order to scale it back to its original size.

I managed to make the upsizing part without too many issues, but can't find a way to reverse the animation, to make the a-video return to its original scale.

Here is what I have so far (adapted for briefness):

<a-video animation="property: scale; to: 20 20 20; dur: 200; dir: alternate; startEvents: startplay" src="#myvid" id="avideo"></a-video>
<a-image src="#play" onclick="document.getElementById('avideo').emit('startplay')"></a-image>
<a-image src="#pause" onclick="????"></a-image> <!-- is it possible to play the animation rewind here since I specified dir: alternate on #avideo? -->

The upscaling animation works fine, but I can't find how to trigger the rewinding part as described in the comments.

I'm fairly new to AFrame, it's probably something simple, but an answer could help rookies like me.

Thank you


Solution

  • I'd try doing it with a second animation:

    • one does what you want
    • the other returns from the current state to the "original" state.

    Lets say with a setup somewhat similar to yours

    <a-sphere animation__play="property: scale; from: 1 1 1; to: 5 5 5; dur: 2000; dir: alternate; startEvents: play-anim; pauseEvents: pauseA-anim; stopEvents: stop-anim; loop: true"
              animation__rewind="property: scale; to: 1 1 1; easing: linear; startEvents: rewind-anim"
              animation-manager>
    </a-sphere>
    

    The animation-manager will be a custom component containing all the logic:

    // custom component declaration
    AFRAME.registerComponent("animation-manager", {
      // called upon initialization
      init: function() {
         // manage pressing the play image / button
         playBtn.addEventListener("click", e => this.el.emit("play-anim"));
         
         // manage the rewind image / button
         rewindBtn.addEventListener("click", e => {
           // set the current scale as the "starting point"
          this.el.setAttribute("animation__rewind", "from", this.el.getAttribute("scale"))
          
          // pause the current animation
          this.el.emit("pause-anim")
          // play the rewind animation
          this.el.emit("rewind-anim")
        })
      }
    })
    

    Check it out here.