Search code examples
animationaframewebvr

How to trigger AFrame animation to specific location from javascript?


For example, how would you implement this: A cube is clicked on and based on a previously defined JS variable (call it point "p"), another cube moves (animates) to that point "p"? In other words, is there a way to define and activate AFrame animations on the fly? Thanks a lot.


Solution

  • You can add a <a-animation> element below your target box. Animation-A-Frame

    <script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.3.2/aframe.min.js"></script>
    <!DOCTYPE html>  
    <html>  
    <head>
    <title>move animation</title>
    <script>
    AFRAME.registerComponent("move",{
    schema : {
      target : { type : "selector"},
      position : {type : "string"}
    },
    init : function(){
    	this.el.addEventListener("click",function(){
                var animation = document.createElement("a-animation");
                animation.setAttribute("attribute","position");
                animation.setAttribute("to",this.data.position);
                animation.setAttribute("dur","1000");
                animation.setAttribute("repeat","0");
                this.data.target.appendChild(animation);
    	}.bind(this));
    }
    
    });
      </script>
    </head>
    <body>
    <a-scene>
      <a-camera  position="0 0 0" universal-controls>
        <a-entity id="cursor" cursor="fuse: true;fuseTimeout:500"
        	material="color:black"
        	geometry="primitive:ring"
        	position="0 0 -1"
        	scale="0.01 0.01 0.01"
        ></a-entity>
      </a-camera>
    <a-box id= "blue_box" position="0 1 -2" color="blue" ></a-box>
    <a-box position="1 1 -2" color="red" move="target:#blue_box;position:-1 0 -5"></a-box>
    </body>
    </html>