The art of manipulating the position and rotation of A-Frame entities

Unfortunately, my knowledge of positioning and rotating entities in 3D space is limited. Therefore, I am interested in developing a function that simplifies the process by using more intuitive parameters like:

createEntity(vertical, horizontal, distance)

to achieve something similar to

<a-entity position="-2 0 -2" rotation="-10 30 0"></a-entity>

where vertical and horizontal are floats between 0 and 360, and distance is a float representing how far the entity should be placed, with higher values indicating greater distance.

The rotation should initially face the camera.

Are there any helper functions available for these calculations?

Answer №1

Utilizing the Spherical coordinate system for element positioning and the look-at component to align objects with the camera is the approach you're looking for.

While there are no predefined helpers available, creating a custom component makes it simple:

// Registering the Component
AFRAME.registerComponent('fromspherical', {
  // User-provided angles and radius will be used in calculations 
  schema: {
     fi: {},
     theta: {},
     r: {},
   },
   init: function() {
     // Converting angles to radians
     let fi = this.data.fi * Math.PI / 180
     let theta = this.data.theta * Math.PI / 180

     // Calculating x, y, z coordinates based on provided data
     let z = (-1) * Math.sin(theta) * Math.cos(fi) * this.data.r
     let x = Math.sin(theta) * Math.sin(fi) * this.data.r
     let y = Math.cos(theta) * this.data.r
     
     // Setting element position using calculated coordinates
     this.el.setAttribute('position', {
       x: x,
       y: y,
       z: z
     })
     
     // Rotating element towards the camera
     this.el.setAttribute('look-at', '[camera]')
   }
 })

View an example in this fiddle.


The order of calculations differs from what you may find on the wiki as AFRAME's XYZ space orientation is unique:

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

By default, the camera points along the negative Z axis upon initialization.


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

Focus on a specific data set within a JSON file when working with Backbone.js

Hello! I am new to learning Backbone.js and would love some suggestions from the experts out there. Here is a snippet of my code: app.Collections.UserCollection = Backbone.Collection.extend({ model: app.Models.IdModel, url: "/test/test_data.json" ...

Using JSON data to populate the jQuery UI Datepicker

Is it possible to populate this jQuery UI datepicker calendar with data from a JSON file containing all non-working days for the years 2017 and 2018? P.S. return [!(month == 8 && day == 27), 'highlight', highlight]; - This example demons ...

Manipulating objects with Jade Mixin

My current challenge involves programmatically displaying objects within a jade template by passing an array of objects to the view. The aim is to present these objects in a grid view with up to 3 items per row. However, I encountered an issue where nested ...

Bizarre JavaScript Comparisons

I encountered an issue with the comparison process. The expected result should be 11 since the cost of the product at index 11 is lower than the cost of the product at index 18. However, the computed result turns out to be 18. var scores = [60, 50, 6 ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Display multiple values in a select dropdown using Bootstrap 5 properties

I am stuck with the following code<hr> HTML <select id="select" placeholder="Choose Select" class="selectpicker" multiple></select> <div class="container"> <div id="all" clas ...

What could be causing my Express API registration route to fail when attempting to POST?

Currently, I'm in the process of developing a compact authentication system for a practice project that I've undertaken. As part of this endeavor, I am sending POST requests via Postman to my Express server located at http://localhost:4000/api/re ...

How to Delete an Added Image from a Dialog Title in jQuery

I've tried multiple solutions from various sources, but I'm still struggling to remove an image from a dialog. Whenever I attempt to do so, I end up with multiple images instead of just one. It's important to note that I only want the image ...

My function doesn't seem to be cooperating with async/await

const initialState={ isLoggedIn: false, userData: null, } function App() { const [state, setState]= useState(initialState) useEffect(()=>{ async function fetchUserData(){ await initializeUserInfo({state, setState}) // encountering an ...

Stay dry - Invoke the class method if there is no instance available, otherwise execute the instance method

Situation When the input is identified as a "start", the program will automatically calculate the corresponding "end" value and update the page with it. If the input is an "end", simply display this value on the page without any modifications. I am in th ...

PHP displays the array returned by Ajax as "[object Object],[object Object]"

When working with Jquery, I am creating two arrays - one embedded inside the other. Here is an example of what it looks like: arrayOne = [{name:'a',value:1}, {name:'b',value:2}] var arrayTwo = [{name:'foo',value:'blah&ap ...

Is the current version of NPM React-router too cutting-edge for your needs

When I use the command npm -v react-router on my React app, it shows version 6.9.0. However, when I check the npmjs page for react-router, the latest version available is 5.0.1. How can this discrepancy be explained? ...

Sync JSON object modifications with the DOM using jQuery (or potentially other libraries)

I am working on developing a web application that would be able to update the HTML elements based on changes in a JSON object. For instance, I have an unordered list with data attributes: <ul data-id="elements"> <li data-id="01">Element 01< ...

Tips for adding additional rows or cells to a table with jQuery

Similar Questions: How to Add Table Rows with jQuery Adding Rows Dynamically using jQuery. I am currently working with a table that contains one row and five editable cells for user input. My goal is to implement an "Add Row" feature using jQuery ...

Struggling to retrieve data from Firebase in React Native?

It's been a challenge for me as a newcomer to React Native trying to retrieve data from a Firebase database. This is the process flow of how my data is handled: 1. A user selects locations and trip details (name, startDate, endDate) --> stored in ...

A guide on implementing nested child routes in AngularJS 2

I have successfully completed routing for two children, but now I want to display nested routes for those children. For example: home child1 child2 | grand child | grand child(1) ...

The appearance of the image on the CanvasTexture seems to be distorted with pixel

I have encountered several questions regarding this issue, but none have provided a solution to my problem. Whenever I upload an image onto the object, it becomes pixelated regardless of the minFilter or magFilter that I apply - and I have tried all of the ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

From Blender to Three.js: Creating Realistic Human Models

I am currently working on integrating an animated 3D character into a web browser. My process involves using MakeHuman 1.02 to create the character, which I then import into Blender 2.74 in .mhx format. I utilize the MakeWalk plugin for Blender to retarge ...