Working with Three.js: Creating a Box3 that is not part of the scene object

Having trouble adding a Bounding Box from an object in a different module. Everything works fine when I write it all in my main function, but once I create the function in a separate file and import it into the main file, it stops working.

The error message I receive is:

Uncaught TypeError: Cannot read properties of undefined (reading 'updateWorldMatrix')
    at Box3.expandByObject (three.module.js:4934:10)
    at Box3.setFromObject (three.module.js:4852:15)
    at camCollision (camColliders.js:68:37)
    at HTMLDocument.<anonymous> (World.js:355:7)

camColliders.js is where I'm trying to place the function, and World.js is my main file.

Below is the function code:

function camCollision() {
      const camBB = new Box3().setFromObject(camSphereDetector);

      const boule1BB = new Box3().setFromObject(boule1Obj);
      boule1BB.name = 'first';
      const boule2BB = new Box3().setFromObject(boule2Obj);
      boule2BB.name = 'second';
      const boule3BB = new Box3().setFromObject(boule3Obj);
      boule3BB.name = 'third';

      const boulesBB = [boule1BB, boule2BB, boule3BB];

      boulesBB.forEach((bbs) => {
        if (bbs.intersectsBox(camBB)) {
          console.log('got it');
        }
      });
    }

    document.addEventListener('mouseup', () => {
      camCollision();
    });

When attempting this in a separate file, I first import objects from another file which are all Mesh.

It seems that the issue arises because I can't create the Bounding Boxes in a separate file since they need to be added to the scene first, and I only do that in World.js. However, the error points to line 68, with the variable for 'boule1BB', which is puzzling because 'camBB' should be causing the problem first?

This is how I create the Box3 (essentially copying position and size information from GLTF objects, as I'm unable to directly obtain a Box3 from them):

const boule1Obj = new Mesh(
    new SphereGeometry(2, 32, 16),
    new MeshBasicMaterial({ color: 'red', transparent: true, opacity: 0 }),
  );
  boule1Obj.position.set(10, -3.5, 0);

My question is, have I correctly diagnosed the issue? Is there a way to create a Box3 in a different JS file, from an object that hasn't been added to the scene yet (even though it should be when the function is called)? Perhaps using a method other than 'setFromObject'? Or am I misunderstanding the actual problem?

To provide some context, the goal is to display information about each model when clicked by the user, intending to use '.name' for each Mesh corresponding to a model. Hence, I prefer not to clutter the main file with these details but rather keep them separate.

I hope this explanation is clear enough and provides adequate detail for a solution to be found. I haven't come across anyone else encountering this issue. If further information is needed, please let me know!

Thank you in advance for your assistance!

Answer №1

It seems that the issue lies in my inability to generate Bounding Boxes in a separate file, as they are required to be included in the scene within World.js.

However, this is not entirely accurate. As a created THREE.Mesh possesses both shape information from its geometry and a default transform (initially positioned at the origin without any scaling or rotation), Three.js has the capability to calculate a bounding box based on this data as if the mesh were present in the scene. I have demonstrated this functionality in a sample CodePen.

In addition, defining an object in one file and then referring to it in another should not pose an issue, provided that the object is accessible and initialized when it is linked.

My suspicion is that you are assigning boule1Obj, boule2Obj, and boule3Obj in World.js. In such a scenario, the imported function may be hoisted before these variables are assigned, causing the function to bind to them as undefined instead of recognizing them properly.

To resolve this, consider modifying camCollision() to accept the bouleXObjs as parameters.

function camCollision(...objs) {
  const camBB = new Box3().setFromObject(camSphereDetector);

  for(let i = 0; i < objs.length; i++) {
    const objBB = new Box3().setFromGeometry(objs[i]);
    objBB.name = `Bounding Box ${i + 1}`;
    if(objBB.intersectsBox(camBB)) {
      console.log("Got it!");
    }
  }
}

Then, invoke the function like so:

document.addEventListener("mouseup", () => {
  camCollision(boule1Obj, boule2Obj, boule3Obj);
});

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

extracting URL parameters using AJAX

I have successfully created an AJAX request using the GET method, passing variables to the URL and receiving a response. Now, I need to retrieve the current URL variables by clicking on a newly created button in order to proceed with further processing. Th ...

Adjust the color of the navbar only after a user scrolls, with a slight delay rather than

My code changes the navbar colors when I scroll (200ms). However, I would like the changes to occur when I am slightly above the next section, not immediately. In other words, what adjustments should I make to change the color in the next section and not ...

Is it possible for asynchronous functions to write to the same object concurrently and result in invalid values?

I have been experimenting with the code below to see if it can cause any issues with the integer i in the object context. My tests so far have not revealed any problems. // Node.js (v10.19.0) const Promise = require('promise') // object access ...

Encountering a problem while verifying pattern using regular expressions

I'm facing an issue when manually checking if my inputs match the specified patterns. Below is the function I am using for this check: if (!$element.attr("pattern")) return true; let pattern = $element.attr("pattern"); le ...

Tips for transmitting an onChange function from a parent component to a child component in material UI

As a newcomer to react and material UI, I am currently working on developing a dropdown select component. My goal is to pass onChange functions to the component from its parent. Despite following the official documentation closely, I've encountered an ...

The inclusion of react-helmet in my Gatsby website is leading to an issue where the element type is considered invalid

Incorporating the Layout component in my app has significantly improved the styling. This is where I introduced react-helmet. This is how the component looks: import React from 'react'; import { Global, css } from '@emotion/core'; im ...

Efficiently handling multiple responses in Express.js per single request

Currently exploring Node.js and working on a bot utilizing Dialogflow. I am aiming to establish a straightforward process: Step 1: Dialogflow sends a POST request with parameter param1 Step 2: My application replies with a waiting message (e.g., "your re ...

Encountering an "unexpected token" error while utilizing the JSOP API in a ReactJS application

I am facing an issue while fetching data from a JSON API, as it is throwing an "Unexpected token" error. Below is the code that I have tried so far. Any help in resolving this problem would be greatly appreciated. Below is the code snippet: var Demo = Re ...

Ways to extract value from all chosen dropdown list elements

<table id="tb_Answers"> <tbody> <tr> <td> <select class="ddl_NextQuestion" name="_ctl0"> <option value="0">End</option> <option val ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

When the user is actively scrolling in the browser, the button will disappear. However, once the scrolling action is completed, the button will gradually fade

Is there a way to hide the button with the id #stats while the user is scrolling, and then have it fade back in once they finish scrolling? It seems like the code below is not working as expected. Any help would be greatly appreciated! <button id="st ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

Trouble with bringing in the solana/web3.js library

After successfully importing the solana/web3.js package and running it within a NodeJS file, everything was working fine. However, things took a turn when attempting to connect this file with basic HTML, resulting in an error being thrown. import { Tra ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Conceal a row depending on a cell's value being equal to zero

Having an issue with hiding rows that have a zero value in the middle cells. The values in the middle cells are dynamically generated from a Google Spreadsheet. The code below successfully hides rows with zero values that I manually input, but it doesn&apo ...

Restore to the prior iteration of jQuery

Encountered an issue after installing two libraries, one updating to jQuery 1.9.1 and the other installing 1.9.2. Found both versions of jQuery in my Scripts folder, so attempted an upgrade-package in nuGet to version 2.0.1. My project still requires com ...

Tips for changing the value of a TextField in React Material

I am faced with a challenge regarding a form that is populated with data from a specific country. This data is fetched from a GraphQL API using Apollo Client. By default, the data in the form is read-only. To make changes, the user needs to click on the e ...

Effective methods to avoid showcasing AdSense advertisements

For the purpose of creating a responsive design, I am attempting to hide an adsense ad unit on smaller screen sizes. Although I am familiar with the method of using css media queries as outlined on Google AdSense support page, I have encountered an error w ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...

"Enhance Your Website Navigation with a Expand/Collapse Menu Using

After stumbling upon this code that allows a menu to collapse when the user clicks on the minus sign, I noticed that it displays all the contents within the Main Item when the page first loads. My goal is to only show the Main Item when the page initially ...