A sophisticated method for retrieving the source object that Box3 was initialized with, to facilitate straightforward camera collision detection in Three.js

Is there a more efficient method to retrieve the original object used to set a Box3 (using Box.setFromObject) once the Box3 detects a collision?

Currently, I am storing the Box3 in an array and then adding the object that was initially used to create the Box3 into a separate array:

var cube = new THREE.Mesh( geometry, material );
cube.name = "box0";
scene.add( cube );
var bbox = new THREE.Box3();
bbox.setFromObject( cube );
bboxList.push(bbox);
bboxObjectNameList.push(cube.name);

I then iterate through both arrays each frame:

for(i=0;i<bboxList.length;i++)
{
  if(bboxList[i].containsPoint(camera.position)) {
    hitName = bboxObjectNameList[i];
    hitObj = scene.getObjectByName(hitName);
  }
}

If anyone has suggestions on a better approach to identify the object associated with the Box3, please share.

Using Three.js r84

Answer №1

What makes the three.js javascript objects stand out is their nature as, well... javascript objects. This enables you to easily assign any property to a Box3, such as specifying the "object they are set from".

To adhere to the conventions of three.js, it would be advisable to utilize a .userData wrapper property for any additional properties you introduce. By doing this, you prevent potential naming conflicts with internal three.js properties that may be introduced in upcoming updates.

In practical terms, your code could resemble something like this:

var bbox = new THREE.Box3();
bbox.setFromObject( cube );
bbox.userData = { sourceObject: cube };

...

if (bboxList[i].containsPoint(camera.position)) {
  hitObj = bboxList[i].userData.sourceObject;
}

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

Utilizing Multiple MongoDB Connections in a Node.js Application

I am facing an interesting challenge in my Node.js project where I need to connect multiple MongoDB databases. Let me share with you my current setup and the issue that is causing me some trouble. Node Version: v6.12.1 Express.js Version: 4.16.2 Mongoos ...

Tips on preventing a lone track in Laravel for Server Sent Events

In my Laravel app, I am exploring the use of Server Sent Events. The issue I have encountered is that SSE requires specifying a single URL, like this: var evtSource = new EventSource("sse.php"); However, I want to send events from various parts/controlle ...

Identifying when an element hovers over a particular section

I am facing an issue with the side dot navigation on my website. The navigation is standard with a fixed position, but I also have two types of sections with different backgrounds - one white and the other black. The problem arises when the dots are not vi ...

Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that ...

Encountering a "Module not found" error when trying to integrate NextJs 13.4 with React Query and the

I encountered some issues while working on a NextJs application that utilizes App Router. The problem arose when we decided to switch from traditional fetching to using React Query in server components. To address this, I created a file called api.ts withi ...

Is it possible to incorporate a fadein animation into a function?

Developing the entire HTML structure using JavaScript is one of my skills. Here is a snippet as an example: function generateHeader () { $('body').append( $('<header>') .attr('id', "main-header") ...

Is it possible to precisely position multiple children in a relative manner?

I am currently developing a custom dropdown menu where I want the parent element to be relatively positioned within the page. The goal is for all the child elements of the dropdown menu (the list items) to appear as if they are part of a select element and ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

Error: Uncaught object in AngularJS ngRoute

I keep encountering an uncaught object error in my browser console while trying to load my AngularJS application. I am unsure if this issue is related to ng-route.js or if it's something else, as the error message only says 'uncaught object' ...

Transforming a canvas into a div element

Hey there, I'm looking to swap out one canvas for another but I'm not sure how it will look on the browser. Any help would be greatly appreciated. <div id="juego"> <canvas width="203" height="256" id="1" class="bloque"></canvas& ...

Error: Attempting to access the 'name' property of an undefined variable is resulting in a TypeError in Material UI

When attempting to display the retrieved data on MUI Autocomplete, I encountered an error that I cannot seem to figure out. The data is fetched from MongoDB, and I simply want to showcase the category names as selectable options. https://i.sstatic.net/cxT ...

What is the best way to retain data after clicking a button?

I am facing an issue where I need to figure out how to add information to a new page when a button is clicked. For example, let's say I have an "add to cart" button and upon clicking it, I want to store some data. How can I achieve this functionality? ...

Showing hidden errors in specific browsers via JavaScript

I was struggling to make the code work on certain browsers. The code you see in the resource URL below has been a collection of work-around codes to get it functioning, especially for Android browsers and Windows 8. It might be a bit sketchy as a result. ...

The sendKeys() method is malfunctioning in Selenium WebDriver

When attempting to enter phone numbers into the designated field, an error is being encountered. Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element The following code snippet is involved: driver.get("https://m ...

Deleting an ID from an array within a document using Node.js Mongoose

In my model document, there is an array that I am working with. I want to be able to remove a specific ID from this array. Is it possible to do so? https://i.sstatic.net/agaD3.png Below is what I attempted. module.exports.RemoveFavourite = async (req, re ...

A guide on adding an onClick listener to a span element dynamically and then saving it to MongoDB

I have been attempting to add an onClick event within a span tag as shown below, with the goal of storing it in MongoDb. However, my event does not seem to be saving and is automatically removed. When I retrieve data from the database, it is not present. H ...

Incorrectly modifying the _locals property while rendering a MySQL result in Express/Node.js leads to the error: "Cannot assign to read only property '_

I am currently using Handlebars to display data retrieved from a MySQL query. The route is set up as shown below: var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; connecti ...

Transform incoming AJAX response into Backbone model

Is there a way to transform the success callback data into a Backbone model? Here is what I currently have: App.Models.Image = Backbone.Model.extend({ idAttribute : 'image_id' }); App.Collections.Image = Backbone.Collection.extend({ model : ...

My script was functioning just fine until suddenly I started receiving the dreaded "No 'Access-Control-Allow-Origin' error" repeatedly

I've been working on building a small API in the background of a server using PHP. The subdomain I'm utilizing for this project is api.website.com. To aid in debugging, I included the following code at the top of my index.php file within the subd ...

Code-behind not functioning properly for Bootstrap Modal

Whenever the password or username are incorrect, I need to open a modal and keep it in the 'Else' statement. However, it is not working, the modal does not open. protected void bntLogar_Click(object sender, EventArgs e) { Registrar c ...