Managing Models in THREE.js

My current project involves loading .obj files using THREE.OBJLoader() and then adding each object to the screen by pushing it into the myObjs[] array.

var myObjs = [];
var loader = new THREE.OBJLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
object.position.x=xpos;
object.position.y = ypos;
scene.add( object );
teeth.push(object);
});
loader.load( 'obj/myobj1.obj' );
loader.load('obj/myobj2.obj');
loader.load('obj/myobj3.obj');

To determine whether an object is clicked or not, I use the following code:

function onDocumentMouseDown( event ) {

event.preventDefault();
var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - (   event.clientY / window.innerHeight ) * 2 + 1, 0.5 );


projector.unprojectVector( vector, camera );

var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( teeth, true );

if ( intersects.length > 0 ) {

intersects[0].object.position.z=50;
}

Everything seems to be working fine, but I'm currently struggling with figuring out how to track which object in the myObjs[] array was clicked. Any ideas on how to map intersects[0].object to myObjs array would be greatly appreciated.

Best regards, ZB

Answer №1

The object will remain the same, meaning both `intersects[0].object` and a member of the `myobjs` array will be pointing to the identical instance. If you need to determine the index within the `myobjs` array (perhaps to remove it from there), you have a few options:

  1. Upon intersection, iterate through the `myobjs` array and compare `intersects[0].object.id` with `myobj[i].id` (each object in three.js has a unique `id` property).
  2. Additionally, you can assign custom properties to the object in your `load` event handler. Just add a line `object.myId = myobjs.length;` just before pushing it to `myobjs`, allowing you to later reference it by `intersects[0].object.myId`.

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

Encountering an issue with Masonry's container.append that is causing an Uncaught TypeError: Object does not possess the filter method

I have implemented infinite scroll on my website to display images. The images are arranged using a tool called masonry. Initially, I only load 10 images into the #container div when the page loads. These images are aligned perfectly with no errors in the ...

How can I incorporate a dashed vertical line in between select bars on a bar chart using Echarts?

I am currently utilizing Echarts and have successfully developed a bar chart. My goal is to incorporate two vertical dashed lines to distinguish between Source3 and Source4, as well as another dashed line to indicate the separation of SourceSix and SourceS ...

What is preventing me from merging these two arrays together?

Here is some code for a Vuex mutation: export const CREATE_PANORAMAS = (state, panoramas) => { console.log('building.panoramas:', state.building.panoramas) console.log('panoramas:', panoramas) state.building.panoramas.concat(p ...

Using React hooks to implement drag and drop functionality

As a backend engineer primarily, I've been struggling to implement a simple drag and drop feature for a slider I'm creating in React. Here's the behavior without using debounce: no-debounce And here's the behavior with debounce: with- ...

Is utilizing a standardized logging system considered a best practice for a node and express application?

I am currently working on a node.js application that consists of several dozen modules and uses bunyan for logging with JSON output and multiple configurable streams. I have been searching for good examples on how to implement a logger instance across all ...

Saving events with a Full Calendar is a seamless process that

I am encountering a problem while trying to save the end time and enable dragging across multiple days on my fullcalendar. I have configured it to save data using jQuery.post to my database, but I am struggling to populate the end value and allow it to be ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

Animating elements on a webpage can be achieved by using both

Is there a way to create an animation that moves objects based on button clicks? For example, when the "Monday" button is pressed, the object with the correct color will move down. If any other button like "Tuesday" is clicked, the previous object will mov ...

Tips for determining the starting horizontal and vertical rotation of a camera for OrbitControls to utilize (Azimuthal and Polar Angles)

Is there a way to set the initial horizontal and vertical rotation of a PerspectiveCamera that the OrbitControl can then use? I attempted to use .rotateX(X) .rotateY(Y) in PerspectiveCamera, but it doesn't seem to have an effect. In the three.js docu ...

Setting the iDisplayLength property in jQuery Datatables to -1 will display all rows in the table

Using jQuery Datatables, I am trying to populate a table with entries from a server via ajax. The data retrieval works perfectly, and I am able to display them in the table. However, I am facing an issue where I want to show all rows/entries at once. I hav ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

Tips for effectively managing errors in Next.js getStaticProps

Currently, I am immersed in the development of my inaugural Next.JS application (Next and Strapi). All functionalities are operational, but I am interested in discovering the optimal approach to integrate error handling within getStaticProps. I have exper ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

Cease the inclusion of the definition file import in the output of TS

I am facing an issue with a third-party library that needs to be dynamically loaded with an authentication key. Since the API is complex, I require type definitions in my TypeScript code for better clarity. In my .tsconfig file, I have set "target": "esn ...

Ways to refresh a nested form

I'm currently learning Ruby on Rails and working on developing a web application. The app consists of a classic model with Users who can create Posts. Another model called Online is used to display the posts on a common wall, and it has an associatio ...

Verifying Content in JavaScript

Here is a snippet of code I used to validate a Registration form on a content page. However, the validation part seems to not be functioning properly. Any assistance would be greatly appreciated. Master Page <%@ Master Language="C#" AutoEventWireup="t ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

The component is unable to access VueJS references

Below is a simplified version of the code I am working with: <html> <head> <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script> </head> <body> <div id="app"> & ...

The function react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext is not recognized when implementing Autocomplete within Material UI

Every time I attempt to create an Autocomplete tag utilizing Material UI, an error pops up, which can be seen in the following link: https://i.sstatic.net/kxKR4.png The Autocomplete code snippet is as follows: import React, {useState, useEffect, useCo ...

Changing the visual appearance of an alert in JavaScript and HTML

My knowledge in JavaScript is limited, but I have a script that retrieves a query from a Python service to a Mongodb database. The query is returned in the following format: [{CHAIN: "STREET ELM, ELMER", CODE: "1234"}, {CHAIN: "STREET LM, LMAO", CODE: ...