deleting a aircraft upon the addition of another in three.js

I am striving to implement a button that toggles between different terrain-generating functions and removes the previous terrain. The current issue I am facing is that the planes stack on top of each other. You can see an image of the problem here.

There are two functions for generating terrain - one creating lava-type terrain, and the other cobblestone terrain. Each function has been encapsulated within its own block.


function lavaGround() {
  const planeLava = new THREE.Mesh(
    new THREE.PlaneGeometry(200, 200, 512, 512),
    new THREE.MeshStandardMaterial({
      //irrelevant code
    })
  );
  scene.add(planeLava);
}

function cobbleGround() {
  const planeCobble = new THREE.Mesh(
    new THREE.PlaneGeometry(200, 200, 512, 512),
    new THREE.MeshStandardMaterial({
    //irrelevant code
    })
  );
  scene.add(planeCobble); 

There are buttons in place which successfully add the new terrain to the scene:

let cobbleButton = document.getElementById("cobblestone");
cobbleButton.addEventListener("click", cobbleGround);

let lavaButton = document.getElementById("lava");
lavaButton.addEventListener("click", lavaGround);

However, when attempting to remove the other terrain using scene.remove, the removal process did not work as intended. Further adjustments were made by trying to consolidate all terrain-related operations into a single function, but this also failed to yield the desired outcome. Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

Depending on how your code is structured:

  • You have the option to include an object and assign it to the mesh that was created (or create a list to add newly created meshes to), allowing you to track which objects were created for easier removal:
    let terrainCreated;

    function lavaTerrain() {
    const lavaPlane = new THREE.Mesh(
      new THREE.PlaneGeometry(200, 200, 512, 512),
      new THREE.MeshStandardMaterial({
        //irrelevant code
      })
     );
      // Check if a terrain exists and remove it from the scene
      if(terrainCreated != null) scene.remove(terrainCreated)
      scene.add(lavaPlane);
      // Store the created terrain
      terrainCreated = lavaPlane
    }

    function cobbleTerrain() {
      const cobblePlane = new THREE.Mesh(
      new THREE.PlaneGeometry(200, 200, 512, 512),
      new THREE.MeshStandardMaterial({
      //irrelevant code
      })
      );
        if(terrainCreated != null) scene.remove(terrainCreated)        
        scene.add(cobblePlane);
        // Store the created terrain
        terrainCreated = cobblePlane 
     }

If these terrains are consistently the same shape when created, you could store both terrains so they can be recycled instead of being recreated every time you call the method, like this:

    let lavaPlane;
    let cobblePlane;

    function lavaTerrain() {
    if(lavaPlane != null) 
    {
       if(cobblePlane != null) scene.remove(cobblePlane)
       scene.add(lavaPlane)
    }
    else{
       const plane_Lava = new THREE.Mesh(
         new THREE.PlaneGeometry(200, 200, 512, 512),
         new THREE.MeshStandardMaterial({
          //irrelevant code
        })
      );
      // Check if a previous terrain exists, and remove it from the scene
      if(cobblePlane != null) scene.remove(cobblePlane)
      scene.add(plane_Lava);
      // Store the created terrain
      lavaPlane = plane_Lava
      }
    }

This approach can be further modified or optimized as needed.

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

Sorting objects in Angular using ng-options

I am working with an object that has the following structure: { 3019: 'Javascript', 3046: 'Css' } After that, I display this object in a select element like this: <select ng-model="langChoosed" ng-options="key as val ...

The behavior of the jQuery click function seems to be quirky and not functioning as expected. Additionally, the

It seems that instead of triggering a POST request, somehow a GET request is being triggered. Additionally, the ajax call is not being made as expected. I have attempted this many times before, but none of my attempts seem to be working. It could potenti ...

Verifying the emptiness of a PHP array using JavaScript

Hey there, I've got a form set up for users to input one or more books into a database. If a user forgets to enter the title when adding just one book, a JavaScript alert pops up reminding them to fill it in. However, if they have two or more books an ...

Loading an Angular app causes Chrome devtools to freeze

Currently, I am facing some unusual behavior in my rather large Angular (1.5) application. When I have Chrome DevTools open while loading the app, the CPU usage of that particular tab shoots up to 100%, causing the app to take a minute or more to load. Add ...

Issue encountered when validating password through submission rate limiting

On my login page, I perform validation on the Email and Password entered by the user using submission throttling from the database. However, I encountered an error stating 'undefined index: txtMail' on the validate page. To track the server-side ...

Node.js method convention - invoking self-defined functions

Consider a scenario where a Node module contains two functions, func1() and func2(). It is necessary for func1 to make a call to func2 during its execution. In order to test func2 independently, I have included both func1 and func2 in the exports by setti ...

Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this: { "3": { "id": 3, "first": "Lisa", "last": "Morgan", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email&# ...

The Context API leaves me feeling lost and confused

I am currently utilizing Auth0 for user sign up. My goal is to extract the user id listed under sub:value, and then add it to my database to associate it with a user's post. To achieve this, I am attempting to utilize a Context API to retrieve the use ...

Smooth scrolling feature for Wordpress websites

I am currently in the process of converting an HTML5 template into a Wordpress theme. One specific feature I'd like to add is a custom scroll for Wordpress using the code: <script src="jquery.nicescroll.js"></script> DEPENDENCIES This cod ...

Is it possible to transfer a Mongo connection to JQuery code using socket.io?

I'm currently working on setting up a global MongoDB connection in my node.js web app. Here is what I have so far: var MongoClient = require('mongodb').MongoClient; var mconn = null; MongoClient.connect('mongodb://myHost:27017/users&a ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Struggling to integrate pdfform.js into a React application

Struggling to integrate the pdfform.js library into my React app. I attempted to use the npm package pdfform, but encountered some difficulties. If anyone has any tips or guidance, it would be greatly appreciated. Check out the pdfform.js library on GitH ...

Unable to set DIV to 'inline-block' or none based on checkbox selection

Despite reviewing multiple examples, I am still struggling to make this DIV visible and hidden by clicking a checkbox. Can someone please review my JavaScript code? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Conten ...

A step-by-step guide on creating JavaScript web resources programmatically in a proper

I'm relatively new to CRM, so please bear with me as I may make some mistakes along the way. Currently, I am attempting to dynamically generate a web resource (specifically in JavaScript or JScript) early bound using OrganizationServiceproxy in the f ...

When dynamically adding an option, the select value becomes empty

I am facing a problem with a select element that I cannot change programmatically. Initially, the select has only one option: The initial HTML structure looks like this: <select id="clients" name="client"> <option>Existing Clients...</ ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

Having trouble loading mtl file in Three.js with map_ks and bump instructions?

I am currently working with an MTL file that contains the following specifications: newmtl blinn_backSG illum 4 Kd 0.17 0.15 0.28 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 bump -s 0.1 0.1 canvas_specular.tif -bm 0.025 Ni 1.00 Ks 0.00 0.00 0.00 map_Ks -s 0.1 0.1 ...

Discover the most frequent value in an array by utilizing JavaScript

My array contains repeating values: [0, 1, 6, 0, 1, 0] How can I efficiently determine the highest frequency of a specific value being repeated? For example, in this array, I would like the script to return 3 since the number 0 repeats most frequently a ...