<!DOCTYPE html>
<html>
  <head>
    <title>Intro Glitch - 01</title>
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    <script src="https://unpkg.com/aframe-environment-component/dist/aframe-environment-component.min.js"></script>
    <script>
      AFRAME.registerComponent("follow", {
        schema: {
          target: { type: "selector" },
          speed: { type: "number", default: 0.8 },
          minimumDistance: { type: "number", default: 1 }
        },

        init: function() {
          this.directionVec3 = new THREE.Vector3();
          this._targetPos = new THREE.Vector3();
          this._currentPos = new THREE.Vector3();
        },

        tick: function(time, timeDelta) {
          var directionVec3 = this.directionVec3;

          this._targetPos.setFromMatrixPosition(
            this.data.target.object3D.matrixWorld
          );
          this._currentPos.setFromMatrixPosition(this.el.object3D.matrixWorld);

          // Subtract the vectors to get the direction the entity should head in.
          directionVec3.copy(this._targetPos).sub(this._currentPos);

          // Calculate the distance.
          var distance = directionVec3.length();
          //console.log(this._targetPos, distance);

          // Don't go any closer if a close proximity has been reached.
          if (distance < this.data.minimumDistance) {
            return;
          }

          // Scale the direction vector's magnitude down to match the speed.
          var factor = this.data.speed / distance;
          ["x", "y", "z"].forEach(function(axis) {
            directionVec3[axis] *= factor * (timeDelta / 1000);
          });

          // Translate the entity in the direction towards the target.
          this.el.setAttribute("position", {
            x: this._currentPos.x + directionVec3.x,
            y: this._currentPos.y + directionVec3.y,
            z: this._currentPos.z + directionVec3.z
          });
        }
      });
    </script>
    <script src="../js/livecode.js"></script>
  </head>
  <body>
    <a-scene environment="preset: tron; playArea: 10">

      <a-sphere
        radius="0.2"
        position="0 1.6 -3"
        follow="target: a-camera; speed: 3"
      ></a-sphere>

      <a-camera></a-camera>

      <a-sky color="#ECECEC"></a-sky>
    </a-scene>
  </body>
</html>