Search code examples
javascriptthree.jsaframewebvr

A-frame limit cameras y distance


I have some code that restricts the camera movement in A-frame so when the camera moves 10 spaces away from the starting point, they are teleported back to the position 0, 1.6, 0. Currently, this works is the players x or y axis moves 10 spaces away from their starting point. How can I modify this so the player is only teleported back if only their y position moves 10 spaces from their starting point? Code:

<!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);
        }
      }
    });
  </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> 

Solution

  • you can even do something like this to not trap into walls at position 4 around you! Here as well with camera movement settings WASD

    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    <script>
        AFRAME.registerComponent('limit-my-distance', {
          init: function() {
              // nothing here
          },
          tick: function() {
            // limit Z
            if (this.el.object3D.position.z > 3.8) {
              this.el.object3D.position.z = 3.8;
            }
            if (this.el.object3D.position.z < -3.8) {
              this.el.object3D.position.z = -3.8;
            }
    
            // limit X
            if (this.el.object3D.position.x > 3.8) {
              this.el.object3D.position.x = 3.8;
            }
            if (this.el.object3D.position.x < -3.8) {
              this.el.object3D.position.x = -3.8;
            }
    
          }
        });
    </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 look-controls wasd-controls="acceleration:10" position="0 1.6 0"></a-camera>
    <a-sky color="#fff"></a-sky>
    </a-scene>