"Selecting an object in Three.js after it has been deleted

Implementing object picking in code is a popular technique:

function Picking(event) {
var raycaster = new THREE.Raycaster();
event.preventDefault();
mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
    if (INTERSECTED != intersects[0].object) {

    }
} else {
     INTERSECTED = null;
}
}

In the scene, there are two objects - cube and sphere. The sphere is closer to the camera than the cube. Sphere has ID1 and cube has ID2. Object picking works correctly.

The issue arises when the sphere is deleted from the scene using 'scene.remove(sphere)'. Even after deletion, the picking function still returns ID1, making it seem like the sphere is still present. What could be causing this problem?

Refer to the example picture: Picture

This code snippet does not produce the desired result:

for (i = sphere.children.length - 1; i >= 0 ; i--) {
       object = sphere.children[i];
       object.geometry.remove;
       object.material.remove;
       object.geometry.dispose();
       object.material.dispose();
       scene.remove(object);
       sphere.remove(object);
   }

or

recur(sphere);
    for (var i in objects) {
        objects[i].geometry.remove;
        objects[i].material.remove;
        objects[i].geometry.dispose();
        objects[i].material.dispose();
        scene.remove(objects[i]);
        sphere.remove(objects[i]);
    }

function recur(obj) {
  if (obj instanceof THREE.Mesh) {
    objects.push(obj);
  }

  for (var i in obj.children) {
    recur(obj.children[i]);
  }
}

The following code adds objects to the scene:

var ObjLoader = new THREE.ObjectLoader();
var ii;
var group = new THREE.Object3D();
var oldModel = scene.getObjectByName('group');
if (oldModel !== undefined) { scene.remove(oldModel); }

      ObjLoader.load("path/model.json", addModelToScene);
      group.name = "group";
      scene.add(group);


function addModelToScene(model) {
     recur(model);
    for (var i in objects) {
        objects[i].castShadow = true;
        objects[i].receiveShadow = true;
    }
    model.name = "ModelName";
    group.add(model)
 }

The .json model consists of multiple objects (1..n) which are added to the group. When picking, the face or material of the cube can be selected but not removed, though its position can be changed.

Thank you.

Answer №1

Adjust your object selection process by storing them in an array right at the beginning:

 /*var objects = [];
  var  group = new THREE.Object3D();
 create your mesh add to array*/
 objects.push(MyMesh);
 /*now we have a reference all the time in objects[0] , objects[1]*/
 objects[0].displose();   check syntax been a while*/

customMaterial = new THREE.ShaderMaterial( 
{
    uniforms: customUniforms,
    vertexShader: document.getElementById( 'vertexShader' ).textContent,
    fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
    //wireframe: true,
    side: THREE.FrontSide 

}   );


function ground (){

var map = new THREE.PlaneGeometry(1024,1024, 128, 128);//Use planebufferGeo

map.dynamic = true;

_terrain = new THREE.Mesh(  map, customMaterial );

_terrain.material.needsUpdate = true;

_terrain.geometry.dynamic = true;

_terrain.geometry.vertexColors = true; 

_terrain.material.uvsNeedUpdate = true;

_terrain.geometry.normalsNeedUpdate = true;

_terrain.rotation.x = -Math.PI / 2;

objects.push(_terrain);

scene.add(_terrain );
}

I applied this approach in a picking game scenario where I stored meshes in an array for easy manipulation of vertices/faces and making changes conveniently. This method simplified comparisons and data checks.

function animate() {

var raycaster = new THREE.Raycaster();

raycaster.setFromCamera(mouse, camera);

var intersects = raycaster.intersectObjects(objects);

if ( intersects.length > 0 ) {
    var faceIndex = intersects[0].faceIndex;
    var obj = intersects[0].object;
    var geom = obj.geometry;
     //etc      

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

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

What is causing the while loop in Mongodb to repetitively insert the same document rather than cycling through the documents?

Currently, I am in the process of redesigning a MongoDB database structure where the reviews for a specific product will be integrated into the product document itself, rather than maintaining separate collections for products and reviews. I have created a ...

Cease the clicking action event

How do I terminate a mousedown function when the mouse is released? $('#manRun').mousedown(function(e3) { var manID = get_id(this); e3.preventDefault(); $(document).on('mousemove.moveMan', function(e2) { ...

Associating the object key and value with distinct attributes within the component

person = {name: 'Alice', age: '19', weight: 52} I'm looking to display both the keys and values from the object in one label and input field respectively. I attempted using Object.entries, but couldn't figure out how to sepa ...

I am currently implementing a unique scrollbar component to enhance the user experience within my list of options displayed in the MUI Autocomplete feature

Seeking a way to integrate a custom scroll feature from this npm package into the list of options for Material UI autocomplete. Consistency is key in my application, and the default scroll appearance on mui autocomplete doesn't quite align with the re ...

What is the best approach to removing a component by utilizing the children prop in React?

I am currently working on a specific scenario: In my project, I have a component called Foo with a property named bar If the bar property is set to true, then I need to display the Bar component that is nested inside the Foo component If the bar prop ...

Maintain the structure of the slick slider during transitions

I am working with the slick slider and aiming to achieve a specific layout for the slider itself. What I require is a structure that looks like this: div div div div div I have managed to implement this design successfully, bu ...

JavaScript and jQuery - Struggling to retrieve checkbox values

In my dynamically generated (ASP) photo gallery, I have multiple checkboxes. Each checkbox is labeled as 'photos' and contains a unique photo ID in its value attribute. Here's an example of how the checkboxes are structured: <form name=" ...

Why isn't the import statement fetching the necessary function for me?

Hello, I am currently utilizing NextAuth for my application: The main file I am attempting to pull data into: [...nextauth].js import NextAuth from "next-auth" import Providers from "next-auth/providers" export default NextAuth({ // ...

Having issues with the script not functioning when placed in an HTML document or saved as a .js file

Even though the database insertion is working, my script doesn't seem to be functioning properly. The message "successfully inserted" appears on the saveclient.php page instead of the index.html. In my script (member_script.js), I have placed this in ...

Navigating to a different directory using Node.js and ExpressJS route mapping

I'm struggling with setting up routing using ui.router. This is the structure of my folders: https://i.stack.imgur.com/Fu0A9.png In the app.js file within the javascripts folder, I have the following code: var app = angular.module('testing&ap ...

Using AngularJS, trigger an httpget request when the value in a textbox is changed

I am currently working on a web service that returns a json file when called with an entry ID parameter. I have successfully created an Angular method to retrieve the data from this service. However, I am facing difficulty in recalling the service when the ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

Tips for controlling or concealing slot elements within child components in Vue Js

I'm working with a named slot: <div name="checkAnswer" class="w-[70%] mx-[15%] flex items-center justify-center" > <button class="p-3 rounded-3xl shadow-md font-bold m-4 px-10 border-2 bo ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

Upon initialization, my data is not being rendered by componentDidMount, instead, it is only displayed during

As a newcomer to React, I am aware that there may be a more efficient way to accomplish this task. Currently, I am trying to display all events associated with a specific group by passing the group's ID as a prop to the Events component. The Events co ...

Can you explain the distinction between using get() and valueChanges() in an Angular Firestore query?

Can someone help clarify the distinction between get() and valueChanges() when executing a query in Angular Firestore? Are there specific advantages or disadvantages to consider, such as differences in reads or costs? ...

Dynamic styling based on conditions in Next.js

After a lengthy hiatus, I'm diving back in and feeling somewhat disconnected. In short, I have encountered a minor challenge. I successfully created a navigation menu pop-out that toggles classname based on the isActive condition in React. However, I& ...

The login function in Nativescript Vue successfully returns a true value

Hello, I am currently using a function that is quite similar to this one with some minor tweaks here. However, I have encountered an issue when trying to log in to my REST API. Even if I input the incorrect username or password, it still authenticates me ...