Search code examples
javascripthtmlcssaframevirtual-reality

A-frame set jump height to a variable


I am making a video game in Aframe and I'm wondering how can I set my jump height to a variable. Here is the code I'm currently using

<a-entity id="rig"
            position="17.5 50.1 0" 
            movement-controls="speed: 0.2;"
            kinematic-body="enableJumps: true;"
            jump-ability="distance: 1.8;"
         
                networked="template:#avatar-template;attachTemplateToLocal:false;"
                spawn-in-circle="radius:3"
            tracker>
    <a-entity camera="far: 1000;"
              wasd-controls
              look-controls="pointerLockEnabled: true;"
              position="0 1.6 0">
        
    </a-entity>
  </a-entity>

What I would like to happen is to set the jump-ability to equal a variable. For example: jump-ability="distance: VARIABLE;" Does anybody know how I can achieve this?


Solution

  • Without any framework (like angular, or react) you can't use js variables within html elements.

    The if you want some external js script to modify the property, you should do this with setAttribute():

    // either use any logic in a js script
    const btn = document.querySelector("button");
    const sphere = document.querySelector("a-sphere");
    btn.addEventListener("click", e => {
      // set the radius to a random number
      sphere.setAttribute("radius", Math.random() * 1 + 0.5);
    })
    <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
    <button style="z-index: 999; position: fixed">RESIZE</button>
    <script>
      // or preferably within a custom component
      AFRAME.registerComponent("foo", {
        init: function() {
          const btn = document.querySelector("button");
          const sphere = document.querySelector("a-sphere");
          btn.addEventListener("click", e => {
            // no need to duplicate the script logic
            // sphere.setAttribute("radius", Math.random() * 1 + 0.5);
          })
        }
      })
    </script>
    <a-scene foo>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
    </a-scene>

    Which changes the radius value each time the button is clicked.