Search code examples
javascripthtmlthree.jsaframewebvr

How to start an animation on an object on clicking another object in a-frame?


I am making a project on WebVR using a-frame in which I have loaded a collada model of a banner and an a-box element. I want to rotate the box about its axis when the model is clicked upon. I used javascript but instead of animating, it just rotated the box directly very unlike to what happens when we use animation tag of a-frame.

<script>

    function changeView() {
        var view = document.getElementById("float");
        view.setAttribute("rotation",
        {
            x: 0,
            y: 360,
            z: 0    		
        });
    }
</script>
<a-scene>
  
  <a-assets>
    <a-asset-item id="floatingbanner" src="models/floatingbanner.dae"></a-asset-item>
  </a-assets>
  
  <a-entity id="float" collada-model="#floatingbanner" position="-2 2 0" scale="0.3 0.3 0.3" onclick="loaddoc()">
  </a-entity>

  <a-box id="box" position="-1 1.5 0" onclick="changeView()" height=".3" depth=".3" width=".3"></a-box>
 
  <a-camera id="view" position="0 0 0">
          <a-cursor color="black"/>
  </a-camera>

<a-scene>


Solution

  • You need to use the <a-animation></a-animation>.

    Define a animation:

    <a-entity>
      <a-entity position="5 0 0"></a-entity>
      <a-animation attribute="rotation"
                   dur="10000"
                   fill="forwards"
                   to="0 360 0"
                   begin="startAnimation"
                   repeat="indefinite"></a-animation>
    </a-entity>
    

    And then emit() the begin event like this :

    function changeView() {
        var view = document.getElementById("float");
        view.emit("startAnimation");
    }
    


    Also try to use the component system, by attaching the script to Your entities:

    AFRAME.registerComponent('foo',{
      init:function(){
      var view = document.getElementById("float");
         this.el.addEventListener('click',function(){
             view.emit("startAnimation");
         });
      }
    });