Modifying the geometry of a three.js object

I have been working on changing the geometry of objects in a three.js scene. I have written code that almost works, where a mouse click triggers the change. However, I am facing an issue where the shape is only updated on the first mouse click, even though the geometry is being modified correctly with each subsequent click. This is using either version 66 or 68 of the three.js library.

I have looked at resources such as Three.js: Completely change object's Geometry and Updating a geometry inside a mesh does nothing but so far, I haven't been able to get my code to work properly.

Here are the relevant parts of my code:

var count = 0, item, geometry;
var geoms = [new THREE.SphereGeometry(2), new THREE.BoxGeometry(3, 3, 3)];


function init() {

    geometry = geoms[count];
    item = new THREE.Mesh(geometry, material);
    scene.add(item);

}

// Mouse click listener.
function handleClick(event) {
    count = 1 - count;
    geometry = geoms[count];
    item.geometry = geometry;

    /* With that next line, on the first click, the sphere
     * becomes a cube (as intended), but further clicks don't
     * change the view anymore, even though item.geometry is
     * modified.
     */
    item.geometry.buffersNeedUpdate = true;

    /* If I try next line instead, I got the following error:
     * "TypeError: l.geometryGroupsList is undefined"
     * from three.js.
     */
    // item.geometry.verticesNeedUpdate = true;
}

Here is a jsfiddle of a (non-)working example. There is a sphere on screen, a click will make it a cube. Further clicks are supposed to switch between sphere and cube, but nothing changes on-screen.

Answer №1

The reason behind this issue remains unclear to me. It seems that once a geometry object is utilized, it cannot be updated on the mesh.

Fortunately, using .clone() solves the problem in this scenario.

item.geometry.dispose();
item.geometry = geometry.clone();

It is essential to call dispose() on the previous geometry object to prevent memory leaks.

We need to find a more efficient solution for this problem.

Answer №2

After testing out various code snippets, I have discovered that this particular piece of code runs the fastest:

  item.geometry.computeFaceNormals();
  item.geometry.computeVertexNormals();
  item.geometry.normalsNeedUpdate = true;
  item.geometry.verticesNeedUpdate = true;
  item.geometry.dynamic = true;

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

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

Refreshing a data object that is shared among Vue components

I've recently started diving into Vue, and I've found myself responsible for tweaking an existing codebase. There's this data.js file that caught my attention, containing a handful of objects holding city information, like: export default { ...

Show or hide a fixed position div using jQuery when clicked

I am new to jQuery and I am trying to create a "full page menu" on my own. However, I am struggling to hide the menu on the second click. I tried using .toggle() but I found out that it has been deprecated. Can someone assist me with this? Thank you so muc ...

Problem encountered with AngularJS html5mode URL functionality

I am encountering an issue with my AngularJS application that does not contain any nodeJS code. The problem lies in removing the # from the URL and I have implemented ui-routes for routing. 'use strict'; var app = angular.module('myapp&apos ...

Enhancing a Stripe customer object with additional metadata

While setting up a payment system using Stripe, I encountered an issue when trying to add metadata to the customer object. Specifically, I wanted to include my workspace id in the metadata property of the customer. However, upon executing the code below, I ...

Vue.js event change method does not initiate the trigger

I have been attempting to implement a change event in my Vue application, where a statement switches between true and false each time I check a checkbox. However, the functionality doesn't seem to be working as expected. This issue arose while follow ...

Chrome browser causing issues with Bootstrap Modal functionality

Hello everyone, I've encountered an issue with the bootstrap 3 modal not functioning correctly in Chrome or Edge browsers. Interestingly, the modal works perfectly fine in FireFox. It's worth mentioning that the modal does briefly appear for a s ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggeste ...

Angular: Exploring the possibilities of condition-based click event implementation

In my component, there are two elements: 'order information' and a 'datepicker'. When clicking on the component, it will display the order information. However, I want to prevent the click event from being triggered if the user clicks ...

React components featuring Material UI icons

I'm in need of assistance. I am looking for the Material UI icons, but I can't seem to find any information on how to obtain them. https://i.stack.imgur.com/FAUc7.jpg ...

When using $.ajax, special characters are not rendered properly, displaying strange symbols instead of accents such as "é" or "ã"

I'm struggling to display the letter "é" using $.ajax and a JSON file. I've tried setting everything up with <meta charset="utf-8"> but all I get is an alert window showing "". Any help is appreciated, just not looking for PHP solutions. H ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

regular expression for replacing only alphanumeric strings

I'm currently developing a tool that tags alphanumeric words based on the option selected from the right-click context menu. However, I am facing issues when a group of words containing special characters is selected. I have been using the following ...

creating dynamic routes with Next.js

I am in the process of creating a Next.js application that showcases a product catalog sorted by categories and subcategories. The category and subcategory information is stored in an array of objects structured like this: const categories = [ { id: ...

Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image. <div class="a"></div> I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-inde ...

Advancing the utilization of custom Angular input fields

I've developed a unique Angular input element that utilizes a textarea as its primary input field. Is there a way for me to pass along the enter key event to the main form? ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Using Rails 5 and Ajax: Comments will only be appended if a comment already exists

I have been working on a new feature that allows users to add comments to articles using Ajax. However, I have encountered an issue where the comment only gets rendered successfully through Ajax if there is already one existing comment. The database commit ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...