Utilizing the tick method in a-frame for dynamically updating object position according to the camera's location

I am currently utilizing A-Frame and aiming to make an object move along with the camera. In order to achieve this, I have created a component that constantly updates the object's position based on the camera's position:

      AFRAME.registerComponent('follow', {
    schema: {
      distance: {type: 'vec3'},
      target: {type: 'selector'}
    },

    tick: function() {
      const targetItem = this.data.target;
      const relativePosition = this.data.distance

      var tempPos = targetItem.getAttribute("position").split(" ").map(Number);

      targetPos = new THREE.Vector3(relativePosition.x + tempPos[0], relativePosition.y + tempPos[1], relativePosition.z + tempPos[2]);

      this.el.setAttribute('position', targetPos)
    }
  });

While using init instead of tick works fine, it only updates once at the beginning of the scene. Strangely, everything breaks when I switch to using tick. Am I implementing it incorrectly? Is there a different approach to consistently update its position?

Thank you in advance!

Edit: I want to clarify that the objective is to have something follow the camera around without being fixed to your view - similar to Navi from Ocarina of Time.

Answer №1

Found the solution from an external source:

To resolve my issue, I had to place my WASD controller on the entity that holds the camera:

<a-entity id="character" position="0 2 3"  wasd-controls look-controls>
  <a-entity id="camera" camera>
    <a-ring radius-outer="0.03" radius-inner="0.02"
            position="0 0 -1"
            material="color: cyan; shader: flat"
            cursor="fuse: true; fuseTimeout: 500">
    </a-ring>
    </a-camera>
</a-entity>

Next, I had to modify the function as follows:

 tick() {
          const targetItem = this.data.target;
          var distance = this.data.distance;
          var targetPosition = targetItem.getAttribute('position');
          this.el.setAttribute('position',{
            x: targetPosition.x + distance.x,
            y: targetPosition.y + distance.y,
            z: targetPosition.z + distance.z
          });

After making these changes, everything worked perfectly!

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

What causes a small variation in the image composition when displaying a PNG file with drawImage?

In the code provided, the image file named "img" was created using Gimp. This image contains a color pixel : rgba=176 99 234 167. However, when displayed in a particular context and then its composition retrieved using getImageData, there is a sligh ...

Having trouble resolving this issue: Receiving a Javascript error stating that a comma was expected

I am encountering an issue with my array.map() function and I'm struggling to identify the problem const Websiteviewer = ({ web, content, styles, design }) => { const test = ['1' , '2'] return ( {test.map(item => { ...

The process of converting a string containing a list of object properties into separate objects using JavaScript

I am trying to transform the following string into actual objects. It seems that JSON.parse is not functioning as expected because all the properties are grouped together in a single string instead of being separate. This text string is retrieved from an A ...

The data provided was deemed invalid with the message, "Requested quantity is unavailable," involving NextJS and Commerce JS

Hey there! I'm currently working on setting up an online store using CommerceJs and NextJS, but I've encountered an issue when processing payments. The error message I'm receiving is: "The given data was invalid." "type: unprocessable_entit ...

Randomizer File Name Maker

I was questioning the behavior of Multer Filename. If Multer stores files with random filenames, is there a possibility of two files having the same name in Multer? In other words, if I am storing files from a large number of users, could the filenames e ...

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

jshint Issue: Module 'underscore' Not Found

My grunt task is running smoothly, yet I keep encountering the following error every time: Loading "jshint.js" tasks...ERROR >> Error: Cannot find module 'underscore' Is there a way to determine the cause of this issue? The /grunt-contrib ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

Ways to monitor automatic data alterations within a Vue JS component

I have a method that updates data within the component itself, for example: Vue.component('component', { template: '#component', data: function () { return { dataToBeWatched: '' } }, methods: { chang ...

Cannot execute the function test()

I'm just diving into the world of JavaScript and have put together a little fiddle with my code. Check it out here. However, I've run into an issue where removing CDATA makes it work fine in fiddle but causes problems in XHTML editors like Eclip ...

Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console. This is the JSON data: { "currentUser": { "image": { "png": "./images/avatars/image-juliusomo.png", "webp": "./images/avatars/image-juliusomo.webp" }, "us ...

I've encountered an issue when attempting to use innerHTML for DOM manipulation

I've been attempting to remove a specific list item <li> from the inner HTML by assigning them proper IDs. However, I'm encountering difficulties in deleting it. How can I delete these list items after clicking on the cross button? Feel fr ...

The issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

Adjust the axis limits automatically when drilling down in data

I am currently working on a chart that features two axes with proportional values. Specifically, the maximum value of the second axis is set to precisely 13.5% of the maximum value of the first axis. To achieve this, I utilized the callback functionality ...

The Facebook API's JavaScript SDK displays the status as 'connected' even after logging out

As I navigate my AngularJS website, I am utilizing the Facebook SDK for JavaScript to facilitate registration forms. After successfully logging in and retrieving the necessary data from my first attempt, I proceeded to register and eventually logged out of ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

How does axios .catch() handle JavaScript errors within Redux middleware?

In my React Redux application, I utilize axios as the client for handling AJAX requests. To manage asynchronous actions, I have implemented middleware that performs the following tasks: Detect promise objects Handle resolving the promise with then() in ...