Adjust the A-frame's jumping height by assigning it to a variable

I'm currently working on developing a video game using Aframe, and I have a question regarding setting my jump height as a variable within the code. This is what I have so far:

<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>

My goal is to assign the jump-ability attribute to be equal to a variable. For instance,

jump-ability="distance: VARIABLE;"
. Does anyone have any suggestions on how I can accomplish this?

Answer №1

When working without any framework such as angular or react, the use of JavaScript variables within HTML elements is not possible. However, external JavaScript scripts can be used to modify properties by utilizing setAttribute():

// Implementing logic in a JS script
const btn = document.querySelector("button");
const sphere = document.querySelector("a-sphere");
btn.addEventListener("click", e => {
  // Setting 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>
  // Alternatively, use a custom component
  AFRAME.registerComponent("foo", {
    init: function() {
      const btn = document.querySelector("button");
      const sphere = document.querySelector("a-sphere");
      btn.addEventListener("click", e => {
        // Avoid duplicating 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>

This setup allows for the radius value to change each time the button is clicked.

Answer №2

Correcting the issues in your code

Your code contains errors that prevent it from working properly.

This is the section of your code causing the problems:

AFRAME.registerComponent("foo", {
  init: function() {
    var acceleration = 100;
    const cam = this.el.sceneEl.camera.el;
    const btn = document.querySelector("button");
    btn.addEventListener("click", e => {
      acceleration = acceleration === 100 ? 25 : 100;
      cam.setAttribute("speed", "mouvement-controls", acceleration);
    })
  }
})
  • You have a typo in mouvement-controls, it should be movement-controls
  • The order of arguments in the setAttribute method is incorrect. It should be like this:
    movement-controls="speed: {acceleration}"
    instead of
    speed="mouvement-controls: {acceleration}"
    . Change the order of arguments
  • Make sure to set the movement-controls on your rig, not the camera
  • Note: setting speed to 100 will make you move at light speed as speed 1 is similar to acceleration 65

Here is a corrected version of your component:

AFRAME.registerComponent("foo", {
  init: function() {
    var acceleration = 1;
    const rig = document.getElementById("rig");
    const btn = document.querySelector("button");
    btn.addEventListener("click", e => {
      acceleration = acceleration === 1 ? 0.1 : 1;
      rig.setAttribute("movement-controls", "speed", acceleration);
    })
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do I actually have to reiterate all these requirements in each route module file?

As I work on developing a more extensive web application, I have come to realize the importance of modularizing my routes into separate files. However, in doing so, I've noticed that I end up duplicating a lot of required modules. Prior to moving the ...

A guide on downloading and hosting Next.js documentation on your local machine for offline access

Can someone guide me on how to download and host the Next.js documentation locally for offline reference? I attempted to clone the Next.js repo containing the docs but all the files in the docs folder are markdown files, which cannot create and serve a l ...

Using track by in ng-repeat function triggers an endless $digest-loop issue

It appears that I am still struggling to grasp the mechanism behind ng-repeat, $$hashKeys, and track by. Currently, in my project, I am working with AngularJS 1.6. The Issue: I have an array of complex objects that I want to display as a list in my view ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

Reduce the height of the tabs bar in the Gnome terminal

After recently installing Lubuntu 16.04 with gnome-terminal, I noticed that the terminal takes up more space on my monitor due to two unnecessary buttons in the top right corner. For avid terminal users like myself, these buttons only add bulk to the tabs ...

Is the line between strict and transitional blurred by HTML5?

After conducting research, it seems like HTML5 has done away with the strict versus transitional differentiation (now always strict). Although I haven't found any explicit mention of this change, it is definitely implied. Can you confirm if this is in ...

Comparing Strings in JavaScript and PHP

Currently, I have set up an Ajax call with a success function that receives a variable from the PHP page like this. Ajax: $.ajax ({ type: "POST", url: "loginrequest.php", data: 'username=' + username + '&password=' + ...

JavaScript is incapable of locating image files

I am encountering Resource Not Found errors for the image files I am attempting to load into var manifest. Despite following the tutorial code closely, I can't seem to identify what is causing this issue... (function () { "use strict"; WinJS.Bin ...

Can default values be assigned to a DTO during initialization?

What is the method to assign default values when a query is empty? In the case where I have this DTO structure for a query: export class MyQuery { readonly myQueryItem: string; } If the request doesn't include any query, then myQuery.myQueryItem ...

The default props defined in the React component's child element are taking precedence over the custom props supplied by the parent component

The font size is being displayed as 20 and the color as 'red', instead of the font size being 12 and the color being 'blue' as specified in the parent component. However, the fontWeight as 'bold' is showing correctly. I have ...

Eliminate any duplicate objects using JavaScript

Is it possible to remove duplicated objects with the same id using methods other than lodash's _.uniqBy? The id value is always changing, so sometimes I need to remove the object with id:123, but other times it will be a different id. import _ from ...

Encountering a "Element is not defined" error in Nuxt when trying to render Editor.js and receiving

I've been working on creating an editor using Editor.js within my Nuxt project, but it seems like the editor isn't initializing properly when I render the page. import EditorJS from '@editorjs/editorjs'; interface IEditor { editor: E ...

The website crashes upon executing this function

Here's a function I've been working on: function Test() { var x = document.getElementById("input").value; var res = ""; var c = 1; var stoc = ""; while (x > 0) { ...

Error: JSON response is returning as undefined

Whenever I attempt to display the height and weight data from an API (), I encounter an issue: Error: TypeError: Cannot read properties of undefined (reading 'metric') If I remove the "items.height.metric", everything runs smoothly, however, I ...

Moving the remaining columns to the following page in PHP: a step-by-step guide

Hello everyone, I've been scouring the internet but have yet to find a solution. I have a code that generates a table. The issue I am facing is that all columns are displayed on one page and I want them to be split into groups of 10 columns per page. ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

'Without the need to refresh the page, assign a JavaScript variable from JSP on the server side.'

I'm looking for a way to assign a JavaScript variable from JSP without triggering a full page reload. While my current code successfully sets the variable, it also causes the entire page to refresh as a side effect. Here's an example in the exam ...

When using v-for with v-if, only the parent elements will be duplicated

I need to dynamically display form elements retrieved from my database. { "name": "Checkbox", "order": 1, "type": "checkbox" }, { "name": "Dropdown", "order": 2, "type": "dropdown" }, { "name": "Radio Buttons", "order": 3, "type": "radio" } ...

Improved way to handle nested if statements in JavaScript

Suppose there exist 3 divs within my HTML document with the following IDs: stepone steptwo stepthree The objective is to first fetch JSON data from the server and load it into the stepone div. If the returned status is '1', then display ' ...

Guide to building a multi-dimensional array from a flat object

My endpoint is outputting data in a specific format: const result = [ {id: 4, parentId: null, name: 'Fruits & Veggies'}, {id: 12, parentId: 133, name: 'Sanguinello'}, {id: 3, parentId: 4, name: 'Fruits'}, {id: 67, ...