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.