Attempting to retrieve the mesh object using A-Frame's getObject3D('mesh') function results in an undefined value after several attempts

In an attempt to obtain a bounding box for an obj-model in A-frame, I came across two helpful links on stackoverflow that I will reference here: How to get bounding box information from a 3D object in A-frame? Any way to get a bounding box from a three.js Object3D? Despite trying the code snippets provided in those links,

AFRAME.registerComponent('bounding-box', {
            init: function(){
                var el = this.el;
                var obj = el.getObject3D('mesh');
                console.log(obj);
                var bbox = new THREE.Box3().setFromObject(obj);
                console.log(bbox.min, bbox.max);    
            }
        })

I received "undefined" from console.log(obj);, so I attempted the approach mentioned in one of the links,

AFRAME.registerComponent('bounding-box', {
    init: function(){
        var el = this.el;
        console.log(el);
        el.setAttribute('obj-model', {obj: 'obj5/1026/1026outside.obj'});
        var obj = el.getObject3D('mesh');
        console.log(obj);
        var bbox = new THREE.Box3().setFromObject(obj);
        console.log(bbox.min, bbox.max);    
    }
})

However, I still didn't achieve the desired outcome. Sometimes placing the code just before the closing tag worked and displayed the correct bounding box information.

<script>
    var el = document.querySelector('#b-model');
    console.log(el);
    var obj = el.getObject3D('mesh');
    console.log(obj);

    var bbox = new THREE.Box3().setFromObject(obj);
    console.log(bbox.min, bbox.max);    
</script>
</body>

I suspect it has something to do with the loading sequence issue, but I am struggling to comprehend the discussion in this post: How to load 3D object at runtime in A-frame? I have tried various methods similar to the ones mentioned above without success. Perhaps my use of el.setAttribute is incorrect? I also attempted using three.objLoader as suggested by Felix, yet I encountered the same problem. I understand that registering a component ensures it only executes after the entity is initialized, which leaves me puzzled. Can someone provide guidance on how to accomplish this task by registering a component rather than using standalone JavaScript at the end? Thank you in advance!

Answer №1

If your model is loading correctly, you may be attempting to access the mesh and bounding box before the model has finished loading.

To ensure everything works smoothly, wait for the "model-loaded" event:

modelElement.addEventListener('model-loaded', (e) => {
  var obj = modelElement.getObject3D('mesh');
  var bbox = new THREE.Box3().setFromObject(obj);
  console.log(bbox)
})

You can also try it out on this glitch or this fiddle using a gltf model.


For primitive shapes, simply listen for the "loaded" event:

<script src="https://aframe.io/releases/1.4.0/aframe.min.js"></script>
<script>
  AFRAME.registerComponent("foo", {
    init: function() {
      this.el.addEventListener("loaded", (e) => {
        var obj = this.el.getObject3D('mesh');
        var bbox = new THREE.Box3().setFromObject(obj);
        const boxHelper = new THREE.Box3Helper(bbox, 0xff0000);
        this.el.object3D.add(boxHelper)
      })
    }
  })
</script>

<a-scene>
  <a-sphere foo color="blue" position="0 1 -4">  </a-sphere>
</a-scene>

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

The image code is not recognizing the image source

In my attempt to dynamically set the image source in an HTML element after creating it with JavaScript, I have made some interesting observations through testing and alert messages: When providing the image src as a fixed filepath during the creation o ...

Implement a function that attaches an event listener to generate a new table row dynamically

I am currently facing an issue with my table that has ajax call functionality to add rows within the tbody element. The table is already set up on the html page. <table id='mytable'> <thead> <tr> <th>First Col</th> & ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

Exploring the integration of data objects within a style tag in Vue.js

I'm currently experimenting with creating a parallax effect using background-position and a data object. <div class="parallaxBanner" :style="{scrollBanner}"> </div> <script> export default { data: function(){ ...

Transferring a value via AJAX that has been modified by a previous AJAX call

In my form, users input values which are used to calculate a result. The calculation is performed through AJAX calls triggered by onchange events on the user-edited fields. This process works as expected. However, there is a hidden field that also gets up ...

Is there a way to collect multiple optional phone numbers dynamically using DOM manipulation?

I have a piece of code here where I am looking to dynamically add additional phone numbers as an optional field. Can anyone help me figure out how to achieve this? <div class="col-12 row border my-2 py-2"> <di ...

Issues with integrating the jsPDF package into a JavaScript project

I'm struggling to solve this issue. I've been attempting to create a program that can download a pdf from a webpage using the jsPDF npm module. After downloading it, I tried importing it in two different ways: Using the node.js require statemen ...

Node.js bypasses unit test validation

As a beginner in BDD with Node.js, I have a controller function defined as follows: var getUser = function(username, done) { console.log('prints'); User.findOne({ 'local.username': username }, function (err, user) { ...

Creating a customized date picker design with Material UI

Instead of displaying the date in DD/MM/YYYY format, I would like to show "Today" text. For example, when using a datepicker, the browser may display a date like 20/1/2009. However, I want it to show "Today" instead of that specific date. ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Is there a way to delete added information using a trigger that has been inserted through ajax?

I created a function in jQuery and Ajax to add information from a separate PHP file to another file. Let's name the destination file "Homepage" and the file with the data "Template". Here is the function I used: var box = $('#infoPageContainer& ...

ExpressJS subclasses are failing to inherit attributes and properties in callback functions

Currently, I am utilizing ExpressJS 4.16 on Node v8.9.4 and have established a base controller to manage default routes with the following example: class BaseController { constructor(name, app, router, data) { this._name = name; this._app = app; ...

Show or hide a div in Vuejs based on checkbox selection

I've been attempting to toggle the visibility of a container div using Vuejs with no success. I've tried two different methods, but neither seem to work for me. Here is Method 1: <body> <div class="checkbox" id = "selector"& ...

Validating dropdown lists with Jquery

Custom Dropdownlist: <div class="col-md-2"> <div class="form-group"> <label for="field-3" class="control-label">Priority</label> <select id="lstpriority" class="custom-selectpicker" data-live-search="true" da ...

"Encountering a delay in the passport authentication callback process

After multiple attempts to solve this issue independently, I have turned to the Stack Overflow community in search of guidance. I am implementing user authentication using passport. It has already been initialized in my main express.js file following the ...

Transforming a THREE.js shader into a PIXI.js shader

I am currently exploring the world of PIXI.js and custom Shaders, and I must admit, it's a bit overwhelming for me. I came across a GLSL Shader (created by DonKarlssonSan) that I would like to convert to PIXI.js in order to compare performance. Any as ...

What is the best way to embed a variable within a Directive HTML block for seamless access by the Controller?

I am facing a challenge with my custom directive that inserts an HTML block onto the page. The issue is to have a variable within this block that can be manipulated based on an ng-click function in my controller. This is what my directive looks like: .di ...

The anonymous function in the Google strategy is not being executed

I am currently working on implementing Passport to allow users to log in to my website using their Google accounts. I am utilizing yarn along with the following relevant packages: [email protected], and passport-google-oauth20@^1.0.0. The issue I am f ...

I am having trouble retrieving the information stored in an Array of Objects. Specifically, I am having difficulty accessing and iterating through each object using a for

Is there a way to extract data from an API individually and retrieve data from an Array? let {Array}=jsonData fetch("https://apis.ccbp.in/city-bikes?bike_name" + search, options) .then(function(response){ return response.json(); }) .then(funct ...

Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error: TypeError: firebase.auth(...).currentUser is null This is the content of my index.js ...