Search code examples
aframe

During button press: Move camera into direction of view


I want to create a simple aframe snippet for smartphones which moves the camera in the direction of the current field of view as long as the screen (or a button on it) is touched. I have already found a very useful piece of code here which continuously moves the camera in the direction of the FoV (see below).

Unfortunately, all my attempts to activate this motion only during a button press have failed (many of the examples I found only used instantaneous events, for example a 'click' or facing a certain object for the first time, but not continuous button presses). Is it even possible to do something like I have in mind? If so, what kind of trigger would I require?

<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/0.5.0/aframe.min.js"></script>
<script src="//cdn.rawgit.com/donmccurdy/aframe-extras/v3.7.0/dist/aframe-extras.min.js"></script>

<html>  

<body>
<script type="text/javascript">
    AFRAME.registerComponent("listener", {
        schema : 
        {
            stepFactor : {
                type : "number",
                default : 0.05
            }
        },

        tick : function()
        {   document.querySelector("a-camera").components.camera.camera.parent.position.add(document.querySelector("a-camera").components.camera.camera.getWorldDirection().multiplyScalar(this.data.stepFactor));
        }

    });
</script>

<a-scene>
  <a-camera position="0 0 30">
    <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"
      listener="stepFactor:0.01" 
    ></a-entity>
  </a-camera>
  <a-grid></a-grid>
<a-box position="0 1 -2" color="blue" move eve></a-box>
</body>
</html>

Solution

  • Try something like this: have a boolean switched by the mouseup and mousedown events, and have the tick execution within a simple if (myBool) condition:

    AFRAME.registerComponent("foo", {
      init: function() {
        this.mousedown = false
        window.addEventListener("mouseup", (e)=> {
           this.mousedown = false
        })
        window.addEventListener("mousedown", (e)=> {
           this.mousedown = true
        })
      },
      tick: function() {
        if (this.mousedown) {
          //do stuff
        }
      }
    })
    

    fiddle here, but it only moves the camera in the x/y axis.