Position object in A-frame based on its width dimension

Is there a way to convert an object’s length into X coordinates? I have a box that dynamically expands with multiple spheres arranged from left to right inside it. My goal is to position the box in the center of the screen so that its center aligns perfectly with the center of the screen. The challenge lies in adjusting the positioning of the box so that it appears at the center minus half of its own width.

Below is the code snippet used to create the box:

for (var i=1; i<=hudItems.length; i++) {
            var newSphere = document.createElement('a-sphere');
            newSphere.setAttribute('radius', .3);
            newSphere.setAttribute('color', '#ECECEC');
            newSphere.setAttribute('position', hudEl.object3D.position.x+offSet*i + ' 0 0');
            newSphere.setAttribute('src', hudItems[i-1].thumb);
            newSphere.setAttribute('translate', "0 0.6 0");

            var sphereShadow = document.createElement('a-image');
            sphereShadow.setAttribute('src', 'radial-shadow-3.png');
            sphereShadow.setAttribute('rotation', '-90 0 0');
            sphereShadow.setAttribute('scale', '1 1 1');
            newSphere.appendChild(sphereShadow);
            hudEl.appendChild(newSphere);
        }
        sceneEl.appendChild(hudEl);

I am open to any suggestions or tips on how to achieve this desired positioning effect, as there might be a well-known method that I am not familiar with yet.

** Update:

I attempted using BoundingBoxHelper - previously, I was creating the HUD element like this:

<a-entity id="hud" position="-1.2 -2.39 -7" pivot="0 0 0" ></a-entity>

I even tried the following to visualize it:

<a-entity id="hud" geometry="primitive: box; width:2; height:2; depth:2" position="0 0 -7" pivot="0 0 0" ></a-entity>

The additional code I implemented is as follows:

var hud = document.querySelector('#hud').object3D;
var helper = new THREE.BoundingBoxHelper(hud, 0xff0000);
helper.update();
    var min = helper.box.min;
    var max = helper.box.max;
    var newX = -1 * (max.x - min.x) / 2;
    hudEl.setAttribute('position', newX + ' 0 0')

However, I encountered this error message: Uncaught TypeError: Cannot read property 'updateMatrixWorld' of undefined at $.setFromObject (three.js:7891) at $n.update (three.js:41123) at c. (tvr2.html:103) at TWEEN.Tween.update (tween.js:399)

It's worth noting that when I log the helper after creation/update, it does not contain a "box" property or geometry.

Answer №1

To begin, determine the bounding box of the object and any of its children. Utilize THREE.BoxHelper for this purpose:

var object = el.object3D;
var helper = new THREE.BoundingBoxHelper(object);
helper.update();

Next, to center the object on the X axis:

var min = helper.box.min;
var max = helper.box.bax;
el.setAttribute('position', {
  x: -1 * (max.x - min.x) / 2,
  y: 0,
  z: 0
});

The complexity increases with rotation, but this is the general approach.

Answer №2

It seems that the information provided here is no longer up to date.

 Currently, I have found success with this code snippet:

This code appears to be functioning correctly for my needs.

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

How can I utilize passed in parameters in Meteor React?

I am trying to figure out how to use two params that I have passed in the following example. Can someone please assist me? updater(layer, item){ this.setState({layer5: <img id="layer5" className="on-top img-responsive center-block" name="layer5" ...

Is there a way to collapse an element by clicking either the content inside the div or the button within the div?

Is there a way to make a button within a newly activated div close it? The existing code seems to have issues with this functionality, and adding new rules or functions has not solved the problem. Any assistance with fixing this issue using vanilla JavaScr ...

Unable to retrieve user attributes (provided as res.locals.user) in express and hbs view

Here is a snippet of code I use to verify user tokens and store the user information in req.locals: exports.isLoggedIn = async (req, res, next) => { if (req.cookies.jwt) { try { const decoded = await promisify(jwt.verify)( ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Mongoose consistently fails to properly save dates

I have created a Mongoose model and included a birthdate field in the following way: birthdate: { type: Date, required: [true, "Please enter a birthdate"], lowercase: true, validate: [isDate, "Please enter a valid birthdate&q ...

Adjusting the StrokeWidth in pixels/em units on fabricjs

When adding a rectangle or circle to the canvas and adjusting the strokeWidth using a range input, how can we determine the value of strokeWidth in pixels, em, or percent? For instance, if we set strokeWidth to 5 within a range of 1-10, how much does the a ...

Leveraging Webpack for the exclusive creation of a vendor bundle

Presently, our AngularJS project relies on Bower for front-end dependencies and the bower-concat Grunt task to merge bower_components into a single libraries.js file. Similarly, we assemble library CSS files into a libraries.css. Looking ahead, we aim to ...

Looking for an easy solution for bundling and vendoring NPM packages?

Full disclosure: My expertise lies mainly in backend development, and I don't have extensive knowledge in front-end technologies. I am in the process of creating a Golang web application that does not use a single page application (SPA) architecture. ...

Is there a way to transpile a dependency within the node_modules directory when using Nuxt 2?

I have come across challenges when transpiling node_modules with Nuxt, but the latest version of Nuxt (2.0) seems to have addressed this issue by introducing a transpile option in the nuxt.config.js file. https://nuxtjs.org/api/configuration-build/#transp ...

Is there a way to display a message box on initial page load only, using JavaScript or jQuery?

I am looking to display a message box only once when a webpage first loads, and then not show it again if the user refreshes the page. The message should appear regardless of whether the user is logged in or not. Is using cookies the only option for achie ...

Utilize FormData by passing it to a separate function and then utilizing it

I have encountered a perplexing issue with my Flask app that involves submitting a form to upload an image to the server. Despite my efforts, I have been unable to find a solution on my own. When I submit the form, I use FormData to create the necessary o ...

JestJS: Async testing isn't halted

I am facing two issues with my jest test: Is there a way to define the Content collection only once instead of repeating it inside the test? I encountered this error: Jest did not exit one second after the test run has completed. This usually indicates ...

Personalizing the arrow positioning of the Angular8 date picker (both top and bottom arrow)

I am interested in enhancing the design of the Angular 8 date picker by adding top and bottom arrows instead of the default left and right arrows. Can someone guide me on how to customize it? Check out the Angular 8 date picker here ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Receive information on browser activity

Is there a way to trigger an event when the following actions occur: Pressing the reload icon in the browser Pressing the Back or Forward icon in the browser Selecting the Reload menu item from the browser context menu Selecting the Reload option from t ...

The Ajax function fails to trigger during the first load of the page

Note: Kindly refer to the update at the end of this question before proceeding. The problem described is specific to IE 11 and emerged after a recent Windows update. Following the installation of 5 updates, including one for IE, I removed the latter hopin ...

Differences between CookieParser and req.cookies in ExpressJS

As I was reading the documentation on req.cookies in expressjs docs, I learned that when the cookieParser() middleware is used, this object defaults to {} but otherwise contains the cookies sent by the user-agent. Then, exploring the details of the Coo ...

No data appears to be populating the Javascript data list, yet no errors are being displayed in

I'm facing an issue where I have data that I'm using to create two arrays, but they both end up empty without any errors in the console. Below is the data: mydata = { "id": "661", "name": "some name", "description": "some desc", ...

steps for signing in to garmin account with javascript

Attempting to set up an Oauth1 login for Garmin using Angular2 and standard http calls, but encountering a pre-flight OPTIONS call error on the initial request to oauth/request_token path. It seems like CORS is not enabled or something similar. Has anyone ...

What is the best way to assign a background color to each tr element using JavaScript?

I have a list of table rows with different background colors like <tr bgcolor="#OC6110"> <tr bgcolor="#000000"> <tr bgcolor="#FFFFFF"> Is there a way to assign unique background colors to each tr element without specifying its id value ...