Necessary to modify the camera's rotation axis within AFRAME

I have incorporated AFRAME into my metaverse application and am attempting to achieve a Third Person Perspective (TPP) for my avatars. I have implemented a rotate-with-camera component on my model so that the avatar rotates when the camera is rotated. Additionally, I have positioned the camera slightly behind the avatar to create a TPP effect, and I have provided wasd controls for both the camera and avatar.

While I have successfully synchronized the movement, the issue arises with the rotation of the camera. The camera seems to be rotating around the origin (position="0 0 0") instead of using the avatar's position as its center.

Below is the register component code that I am utilizing:

AFRAME.registerComponent("rotate-with-camera", {
tick: (function () {
// create once
const tmpq = new THREE.Quaternion();
const tmpe = new THREE.Euler();

return function (t, dt) {
  if (!this.el.sceneEl.camera) return; // ignore when there is no camera
  const cam = this.el.sceneEl.camera.el; // get the camera entity
  cam.object3D.getWorldQuaternion(tmpq); // get the world rotation
  tmpe.setFromQuaternion(tmpq, "YXZ");
  // set attribute is necessary for wasd-controls
  this.el.setAttribute("rotation", {
    x: 0,
    y: (tmpe.y * 180) / Math.PI,
    z: 0,
  });
};
})(),
});

The following is the camera and avatar setup in my code:

<!--Camera -->
  <a-entity look-at=".avatar"  look-controls="pointerLockEnabled: false" wasd-controls="acceleration:12;">
    <a-entity camera="near:0.01;" position="4 1.72 177.5"></a-entity>
  </a-entity>

  <!-- Avatar -->
  <a-entity class="avatar" >
    <a-gltf-model
    id="player"
    src="#boyBlue"
    position="4 0.12 175"
    animation-mixer="clip:Idle"
    wasd-controls="acceleration: 12"
    rotate-with-camera
    >
    </a-gltf-model>
  </a-entity>

I am looking to have my camera rotate based on the avatar's position. How can I achieve this?

Answer №1

The reason this is occurring is because your camera is offset in relation to the parent entity:

https://i.sstatic.net/t6TZP.png


An easy fix would be to adjust the offset within the parent entity:

<a-entity look-controls wasd-controls="acceleration:12;" position="4 0 0">
<a-entity camera="near:0.01;" position="0 1.72 177.5"></a-entity>
</a-entity>

Check out the glitch here for more details.


For a more optimal solution, it is recommended to refer back to the helpful response where you discovered the component. Implementing a JavaScript controller to position the camera behind the box instead of synchronizing positions, both equipped with wasd controls, would be ideal.

The code snippet for the controller is straightforward:

AFRAME.registerComponent("follow-target", {
  schema: {
    target: {type: "selector"}
  },
  tick: (function() {
    // initialize
    const tmpv = new THREE.Vector3();

    return function(t, dt) {
      if (!this.data.target) return; // do not execute without a target
      const target = this.data.target.object3D; // obtain the mesh
      // monitor the position
      const position = target.getWorldPosition(tmpv); // get global position
      this.el.object3D.position.lerp(tmpv, 0.5) // interpolate linearly towards the global position
    }
  })()
})

Explore the glitch here for further insights.

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

Encountering a problem with the getJSON() function within the app.js file connected to a solidity

Currently, I am working on developing a simple dapp in Truffle. However, I encountered an error when using $.getJSON() function in my app.js file. Below is a snippet of my app.js: App ={ web3Provider: null, contracts: {}, init: function (){ return A ...

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

Tips for converting a "callback pyramid" into a promise-based structure

I'm currently struggling with understanding how to refactor my code to use promises or the Q library effectively. Let's consider a common basic example: I have a test case that imports the same file twice into a MongoDB database and then checks ...

"React-router is successfully updating the URL, however, the component remains un

I am currently working on a React application that includes a form for users to fill out. Once the user clicks the submit button, I want them to be redirected to a completely different page. Although I have only focused on the visual design at this point a ...

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

Exploring the integration of d3 in an Express application - encountering an error: document is not recognized

I am facing a challenge in my expressjs application where I need to dynamically render vertices in a graph using d3. However, the code execution order seems to be causing issues for me. When attempting to use the d3.select function, I encounter the followi ...

Using AngularJS to implement ngView within a custom directive

I've been attempting to implement ng-view within a custom directive, but it doesn't seem to be functioning properly and I'm not receiving any console errors. Here's the code for my directive: (function() { 'use strict'; ...

Tips for determining if a player (canvas) is in contact with a drawn wall for collision detection

I created a 2D map using the canvas HTML element where I drew a red square to represent the player and a light blue wall underneath it. I am looking for a way to detect if the player (red square) is in contact with the wall (light blue). The elements do no ...

Integrate geographic data in GeoJSON format into a Leaflet map by using the Django template

In my Django view, I am fetching results of an SQL query and rendering it on the index.html page of my web map. The POST request successfully returns the acreage calculated from the SQL query to the page. I am also attempting to display the geojson data fr ...

A guide on iterating through an array in vue.js and appending a new attribute to each object

To incorporate a new property or array item into an existing virtual DOM element in Vue.js, the $set function must be utilized. Attempting to do so directly can cause issues: For objects: this.myObject.newProperty = "value"; For arrays: ...

Steps to alter the color of a JSONLoader-generated object with a simple click

Recently, I've been delving into Three.js and managed to create an object using the JSONLoader. The material of the object is currently grey in color. My goal now is to allow users to change the color of the object by clicking on a button that I have ...

What sets apart +variable+ and ${variable} in JavaScript?

Just starting to code and eager to learn. While I was taking in a lecture, I came across this interesting snippet of code: var coworkers = ['go', 'hello', 'hi', 'doit']; <script type="text/javascript&q ...

Glitch in transmitting server data to client in MERN stack development

I am currently developing a MERN web application and I've encountered a bug in which the data retrieved from the server is not matching what is expected when making a GET request on the client side. Below is the controller function on the server for ...

Struggling to locate the index of the matching object within an array of objects?

There is a dataset available: var data = { "variants": [{ "quantity": "20", "varientId": 8, "currency": "YEN", "extraField": { "Size": "1 ...

AngularJS - issue with directive functionality on dynamically inserted classes

Check out this plnkr - I've got a button that toggles the class toggled on the body element. I've also developed a directive to trigger an alert when the toggled class is applied to the body element, but for some reason it's not working. H ...

Generate a JSON array containing objects consisting of a combination of string and boolean values

My goal is to generate a list containing objects with names and boolean values by utilizing AJAX. This process is initiated in the following manner: $('.si-accordion').click(function () { $(this).siblings('.accordion_tab&apo ...

Dependencies in Angular

After diving into Angular recently, I've been grasping the concepts well. However, one thing that still puzzles me is dependency injection. I'm unsure whether it's necessary to declare all components of my application (services, controllers ...

Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Ad ...

Ways to detach event listener in Vue Component

One of my Vue2 components has a custom eventListener that I added in the mounted lifecycle hook. I am now trying to figure out the correct way to remove this listener when the component is destroyed. <template> <div> ... </di ...

What is the best method for securely storing and managing refresh and access tokens within a node.js application?

Currently, I am working with next.js and I am looking for a way to persist an API refresh token without using a database in my application. What would be the recommended practice for storing this token securely so that it can be updated as needed? Storin ...