Utilizing Repurposed Three.js Shapes

I have been experimenting with Three.js to visualize the path of a particle in a random walk. However, I encountered an issue where geometries cannot be dynamically resized so I had to come up with a workaround by removing the existing line from the scene, modifying the geometry, and adding a new line back into the scene. Here's the snippet of code that implements this:

var step = .5;

var material = new THREE.LineBasicMaterial({ color: 0x0077ff }); 
var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3(0, 0, 0) );
scene.add( new THREE.Line(geometry, material));

var render = function() {
  requestAnimationFrame(render); 
  renderer.render(scene, camera);
  controls.update();
}

function addStep() {
  scene.remove(scene.children[1]);
  last = geometry.vertices[geometry.vertices.length - 1];
  geometry.vertices.push(new THREE.Vector3(last.x + (2 * Math.random() - 1) * step,
        last.y + (2 * Math.random() - 1) * step, last.z + (2 * Math.random() - 1) * step));
  scene.add(new THREE.Line(geometry.clone(), material));
}

setInterval(addStep, 500);
render();

This piece of code functions properly, however, it is crucial to clone the geometry at each step for it to work correctly. If we were to replace the last line in addStep() with

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

then calling it multiple times before rendering commences will result in additional line segments being added successfully. Yet, if called after rendering has begun, nothing shows up on the screen.

It seems like there might be a simple solution related to graphic buffers or variable assignments that could resolve this, but I am unable to pinpoint it. I would greatly appreciate any insights on why reusing the modified geometry without cloning is not feasible.

Answer №1

@SarahSmith Check out this jsFiddle link for a modified version of the code you provided:

http://jsfiddle.net/sarah/u6y4n67q/

function updatePosition() {

    points = mesh.geometry.vertices;
    lastPoint = points[ points.length - 1 ];
    points.push( 

        new THREE.Vector3( 
        lastPoint.x + ( 2 * Math.random() - 1 ) * increment,
        lastPoint.y + ( 2 * Math.random() - 1 ) * increment, 
        lastPoint.z + ( 2 * Math.random() - 1 ) * increment ) 

    );

    mesh.geometry = new THREE.Geometry();
    mesh.geometry.vertices = points;

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

}

In this revised snippet, we are using new THREE.Geometry() instead of cloning the geometry object.

It seems that in Three.js, geometry is closely linked to its buffer representation. Therefore, creating a new instance or cloning it is necessary for any edits to take effect.

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 jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

What could be the reason for the individual components not being populated within the listItem?

*** I am iterating through an array and calling the ListItem component for each item. However, only one ListItem is being populated when there should be 3. Can someone please help me figure out what's wrong? *** Here is my code in App.js *** import F ...

Combining two items from separate arrays

How can I efficiently merge objects that share the same index in two different arrays of objects? Below is the first array const countries = [ { "name": "Sweden", "nativeName": "Sverige" }, ...

Using Nest JS to create two instances of a single provider

While running a test suite, I noticed that there are two instances of the same provider alive - one for the implementation and another for the real implementation. I reached this conclusion because when I tried to replace a method with jest.fn call in my ...

When using Python Selenium, we can see JavaScript in the view page source, but inspecting elements reveals the

I'm currently facing a challenge in accessing links to attachments for a web automation project. The issue lies in the fact that while I can view the HTML Code (divs and tables) when loading the webpage via Chrome and inspecting element, all I see in ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

JavaScript error: Undefined variable or function

I'm facing an issue with the following code. When I position the brace in different places, I encounter errors like "var not defined" or "function not defined". My goal is to convert an array into a string so that I can analyze the data and decide how ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

Having trouble with selecting JS dropdown options in Python Selenium

My HTML view- Check out the website design HTML code- View the HTML code here When I click on the dropdown arrow, a new code appears - view the code snippet Although my code successfully displays the dropdown options, it does not allow for selecting an ...

Utilize a WCF Service with HTML and JavaScript

FILE WebService.svc.vb Public Class WebService Implements IWebService Public Function Greetings(ByVal name As String) As String Implements IWebService.Greetings Return "Greetings, dear " & name End Function End Class FILE IWebServ ...

Retrieve only the most recent input value

Currently, I am working with a text input to capture user input. As of now, here is my code snippet: $(myinput).on('input', function() { $(somediv).append($(this).val()); }); While I want to continue using the append function, I am facing an i ...

Why is the parameter declared if its value is never even used? Seems redundant

When trying to send an email, I've encountered an issue with my controller method: const send = function (subject, template, to, options) { // While VSC points out that "subject" is declared but its value is never read, // it does not signal ...

How to transfer data from JavaScript to PHP using AJAX

After spending countless hours attempting to make this function properly, I have come to you for assistance :) I have created a PHP page that can exhibit files from a server. I am able to modify the files using an editor plugin, where the Textarea tag is ...

What is the method for generating dynamic objects from configuration data with Ext JS?

Working with Ext Js to develop a dynamic web application can be quite challenging. When making an AJAX call to fetch data from the server, it's often unclear what the data will be until it is received. While some examples suggest adding dynamic object ...

Encountering a ReferenceError while attempting to implement logic on a newly created page

I've been experimenting with building a website using the Fresh framework. My goal was to add a simple drop-down feature for a button within a navigation bar, but I'm struggling to figure out where to place the necessary code. I attempted creatin ...

What is the best way to search for a specific item in Express.js?

I recently got the Leaderboard API issue fixed, but now I'm encountering a new problem with express Querying. Specifically, I'm attempting to search for a specific Discord ID using quick.db as my database. I've included an excerpt of my expr ...

The implementation of a custom event for jQuery rows is not functioning as expected

I need assistance with jQuery code to add click events only to columns in a row that have text in the first column. Specifically, I want to hide rows containing "1/" in the first column when clicked on for the first row. <table class="results"> < ...

Is it possible to generate HTML form fields with fixed positions when using Orbeon forms?

Is there a way in Orbeon forms to position input fields at specific coordinates, relative to a background image? I currently have a paper form that fills an entire page. My goal is to use the scanned image of this form as a background and then overlay inp ...