I am working with a three.js canvas that contains circles moving independently. Initially, these circles are connected by a single line that follows the same geometry as their positions.
However, I am facing difficulty updating the line's geometry when these circles move.
I have tried searching through all the scene's children to find any child named 'item' and updating their x & y positions. Yet, when attempting to update the line's geometry, it either disappears or remains static (as seen in the code below).
How can I effectively update the line's geometry on each frame to match the movements of the circles?
var container;
var camera, scene, renderer;
var numItems = 40;
var xspeed; // Speed of the shape
var yspeed; // Speed of the shape
var lineGeometry;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
scene = new THREE.Scene();
scene.background = new THREE.Color(0xff3000);
var geometry = new THREE.CircleBufferGeometry(15, 20);
lineGeometry = new THREE.Geometry();
for (var i = 0; i < numItems; i++) {
var item = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0x000000 }));
item.position.x = (-180) + (i * Math.random() * (80 - 1) + 1);
item.position.y = (-50) + (i * Math.random() * (80 - 1) + 1);
item.xspeed = Math.random() * (2 - 1);
item.yspeed = Math.random() * (1 - 0.5);
item.name = "item";
scene.add(item);
lineGeometry.vertices.push(item.position);
}
var line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({ color: 0x000000 }));
line.name = "line";
scene.add(line);
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
for (var i = 0; i < scene.children.length; i++) {
var newPosition;
if (scene.children[i].name === 'item') {
scene.children[i].position.x = scene.children[i].position.x + scene.children[i].xspeed;
scene.children[i].position.y = scene.children[i].position.y + scene.children[i].yspeed;
newPosition = scene.children[i].position;
if (scene.children[i].position.x > window.innerWidth/2 || scene.children[i].position.x < -window.innerWidth/2) {
scene.children[i].xspeed = scene.children[i].xspeed * (-1);
}
if (scene.children[i].position.y > window.innerWidth/2 || scene.children[i].position.y < -window.innerWidth/2) {
scene.children[i].yspeed = scene.children[i].yspeed * (-1);
}
}
if (scene.children[i].name === 'line') {
scene.children[i].vertices = newPosition;
}
}
camera.position.x = 0;
camera.position.z = 1000;
renderer.render(scene, camera);
}