Search code examples
javascriptthree.jsaframe

if touching object move to location aframe


I am wondering how it would be possible in aframe if the camera reaches 20 spaces away from the point 0 0 0 to teleport them back to that point. Would something like this be easy to achieve or difficult? How can I achieve this.


Solution

  • You can get the position of the object using el.object3D.position - that would return x,y,z vector or you can use el.object3D.position.x (or .y / .z for just one axis).

    You can also set the position using the same function el.object3D.position.x = 23.12.

    As @Piotr Adam Milewski said, you would need to calculate the distance - you could use the following expression distance = sqrt(x^2 + y^2 + z^2) or use the THREE.Vector3.distanceTo() then compare it to some value and set the position accordingly (camera default position is 0, 1.6, 0 and not 0, 0, 0).

    A very simple example:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
      <meta charset="UTF-8" />
    </head>
    
    <body>
      <script>
        AFRAME.registerComponent('limit-my-distance', {
          init: function() {
            this.zero = new THREE.Vector3(0, 0, 0);
          },
          tick: function() {
            if (this.el.object3D.position.distanceTo(this.zero) > 10) {
              this.el.object3D.position.set(0, 1.6, 0);
            }
            //this.el.object3D.position.x += 0.1;
          }
        });
      </script>
      <a-scene>
        <a-sphere position="0 2 -10"color="red"></a-sphere>
        <a-plane color="green" position="0 0 -5" rotation="-90 0 0" width="20" height="20"></a-plane>
        <a-camera limit-my-distance></a-camera>
        <a-sky color="#fff"></a-sky>
      </a-scene>
    </body>
    
    </html>