Create a function that reverses the process of removing mesh

I have a function that creates mesh when you click on another. Upon clicking, 2 or 3 meshes are created and move to their positions. Now, I want to implement the reverse function: when the meshes are deployed and you click on them again, the previously created meshes should move back and be removed from the scene.

Below is my initial function:

function deploySphere(element, obj) {


    var matStdParams = {
        roughness: 1,
        metalness: 0.8,
        color: element.group,
        emissive: element.group,
        emissiveIntensity: 0.5
    };


    var sphereMaterial2 = new THREE.MeshStandardMaterial(matStdParams);

    var mesh = new THREE.Mesh(sphereGeometry, sphereMaterial2);

    mesh.position.x = x;
    mesh.position.y = y;
    mesh.position.z = z;

    mesh.userData.children = element.children;
    mesh.userData.name = element.label;
    mesh.userData.rang = element.rang;
    mesh.userData.def = element.definition;
    mesh.userData.posx = element.posx;
    mesh.userData.posy = element.posy;
    mesh.userData.posz = element.posz;
    mesh.userData.parent = obj;
    mesh.userData.cartabs = element.cartabs;
    mesh.position.normalize();
    mesh.position.multiplyScalar(1 / element.rang);
    mesh.scale.set(1 / (element.rang / 2), 1 / (element.rang / 2), 1 / (element.rang / 2))

    mesh.position.x = obj.position.x;
    mesh.position.y = obj.position.y;
    mesh.position.z = obj.position.z;

    var x = element.posx;
    var y = element.posy;
    var z = element.posz;


    new TWEEN.Tween(mesh.position).to({
            x: x,
            y: y,
            z: z
        }, 1000)
        .easing(TWEEN.Easing.Elastic.Out).start();


    console.log(mesh);

    scene.add(mesh);
    deployedMeshes.push(mesh)


    // lines
    var material = new THREE.LineBasicMaterial({
        color: 0xffffff
    });

    var geometry = new THREE.Geometry();
    geometry.vertices.push(
        obj.position,
        new THREE.Vector3(x, y, z)
    );

    var line = new THREE.Line(geometry, material);
    scene.add(line);

    gen1 = [];
    gen2 = [];
    gen3 = [];
    gen4 = [];
    gen5 = [];


    obj.userData.bool = true;

};

It's important to note that each mesh contains information about its state: userData.bool (true if deployed, false if not).

Now, how can I make them move back?

Here is my current attempt:

    function removeSphere(element, obj) {
    console.log("--- removeSphere / starting function")


    for (i = 0; gen1.length > i; i++) {

        if (gen1[i].userData.children) {


            for (j = 0; gen1[i].userData.children.length > j; j++) {

                console.log(gen2[i][j]);
                scene.remove(gen2[i][j]);}

        } else {

            scene.remove(gen1[i])

           console.log(gen1[i].userData.children)
        }
    }
};

Thank you for your time.

Answer №1

When utilizing tween.js, you have access to its .onUpdate() and .onComplete() methods.

This example serves as a starting point rather than a definitive solution.

We begin by creating a container for our base objects:

var bases = new THREE.Group();
scene.add(bases);

Next, we define an event to create our base objects when a button is clicked:

btnAdd.addEventListener("click", setBase);

The setBase() function is as follows:

var rndBase = function() {
  return THREE.Math.randFloatSpread(10);
}

function setBase() {
  var base = new THREE.Mesh(new THREE.SphereGeometry(.5, 8, 4), new THREE.MeshBasicMaterial({
    color: Math.random() * 0xffffff
  }));
  base.position.set(rndBase(), rndBase(), rndBase());
  bases.add(base);
}

We can now interact with the base objects by clicking on them using the mousedown event listener:

window.addEventListener("mousedown", setOrRemove, false);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersects;
var obj;
... (additional code) ...

The process of setting children objects is where the fun begins:

function setChildren(parent) {
  ... (code for creating children) ...
}

Removing a base object and its children involves:

function removeObj(baseObj) {
  ... (code for removing children and base object) ...
}

Lastly, remember to include TWEEN.update(); in your animation loop to ensure proper functionality. :)

jsfiddle example r86.

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

Download a JSON file from an angularjs client device

I'm in the process of adding offline functionality to a Cordova app I'm developing. I have a PHP file that retrieves a list of images as JSON, which I then save on the client device using the FILESYSTEM API. However, when I try to display the ima ...

Arranging a dropdown list of options in alphabetical order using Javascript

Could you assist me in sorting my select list alphabetically? Below is the code I currently have:- $.getJSON("php/countryBorders.geo.json", (data) => { $select.html(""); for (let i = 0; i < data["features"].leng ...

Loading Datatables using PHP to send JSON data

I seem to be facing some difficulty in troubleshooting the issue within my code. Currently, I am working on a search script and would like to display the results using Datatables. I have a search form that sends data to my PHP file which then returns a JS ...

Navigating to a different state key within a state object in React - a simple guide

Trying to dive into React, I encountered an issue. My goal is to create my own example from a tutorial. import React, { Component } from 'react'; class MyComponent extends Component { state = { persons: [], firstPersons: 5, variab ...

What is the best way to update objects in different scopes within AngularJS?

Exploring AngularJS for the first time, I find myself struggling with understanding scopes. My current dilemma involves modifying an object or variable from multiple scopes. Here's the scenario: I'm looking to centralize the user notification Co ...

Transmit information to the client-side webpage using Node.js

One of the main reasons I am diving into learning Node.js is because I am intrigued by the concept of having the server send data to the client without the need for constant querying from the client side. While it seems achievable with IM web services, my ...

The media parameter seems to be malfunctioning when attempting to send it to the Kaleyra API using code

Attempting to send media through the Kaleyra API using my code is proving unsuccessful. However, when I make the same request via Postman, it works perfectly fine. async whatsappAPIWithAttachment(requestBody) { let api_key = ""; if (requ ...

Dreamweaver fails to display complete code suggestions

For illustration purposes in Dreamweaver CS6: <script src="libs/Three.js"></script> <script> var scene = null, function init(){ scene = new THREE.Scene(); scene. //a few code suggestions appear, not a ...

"Exploring the depths of sub directories in Node.js: A guide to printing

Once again, I find myself stuck with node.js and in need of your assistance. I am attempting to write a script for the command line interface that will search for all subdirectories under the current directory (process.cwd), and only print out those that ...

Utilizing a Jquery plugin for enhanced form validation with the inclusion of supplementary techniques

I am looking to integrate a jQuery plugin into my form validation process, specifically to ensure that only letters are allowed in the name section. If a user enters special characters or numbers, I want the form to display an error message. Additionally, ...

Generate interactive SVG graphics using d3.js on the server side

My goal is to implement javascript code that gets triggered when an action is performed on an SVG element generated within NodeJS using d3@3. However, I am facing an issue where the on('click') function is not working as expected. router.get(&ap ...

Managing promise chain within the constructor of a React component

I am experiencing an issue with my API data fetching process. The challenge occurs because the rendering takes place before the constructor has completed fetching the data. As a result, the this.todo being sent to the List component ends up being empty. ...

Is there a way to automatically increase a value by clicking on it?

Check out this code snippet I'm working with: let funds = document.createElement('funds') funds.style.color = 'green' funds.style.textAlign = 'center' funds.style.fontSize = '50px' funds.style.backgroundCol ...

The issue persists where Chrome WebAPI's chrome.webRequest.onBeforeSendHeaders is failing to modify the parameters in the outbound requests

I have been attempting to include an IP address in the X-Forwarded-For parameter within the requestHeader, but my code does not seem to be working based on the examples provided in the Chrome API. Below is the code snippet I am currently using: var reque ...

What happens to PHP echos when you send a post request to a web page?

I have a question that may seem silly to some. As someone who is relatively new to PHP, I am attempting to view echo statements from a page that I am posting to but not actually navigating to. Directly accessing the page's URL without the necessary po ...

Problem: Repeated attempts to open the popup are unsuccessful

Developed a leaflet map featuring markers that open popups when clicked. Also integrated a search bar for marker searchability. However, encountering an issue where each popup can only be opened once and on selecting a marker name, the zoom functionality w ...

Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that th ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Using ES6, when utilizing array map in ReactJS, the function does not produce a return value

One challenge I'm facing involves mapping an array to find a specific string value. Unfortunately, despite my efforts, the map function is not returning anything as expected. class Application extends React.Component { constructor(){ super(); ...

Issue with by.cssContainingText function not performing as intended

I have a container that I want to be able to click on. Here's how it looks: <div class="CG-Item CG-B-Left ng-binding" ng-bind="SPL.showTitleText">My New SPL</div> So I am trying to use this code to click on it: element(by.cssContainingT ...