What could be causing vertices in Three.js to not update?

I currently have a loop of circles that are moving independently. My goal is to draw lines from the center of the canvas to each circle's location. The issue I am facing is that the lines are not updating their vertices correctly during rendering, even though I have set

testLine.geometry.verticesNeedUpdate = true
. Upon inspection, it appears that this property remains false.

var container;
var camera, scene, renderer, lines=[], items =[];

var numItems = 40;
var xspeed;
var yspeed;
var lineGeometry;
var testLineGeometry;

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( 0xf7f7f7);
  var geometry = new THREE.CircleBufferGeometry( 20, 20 );
  lineGeometry = new THREE.Geometry();
  var testLineGeometry = 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 = (Math.random() * 20.1 - 1);
    item.position.y = (Math.random() * 20.1 - 1);
    item.xspeed = Math.random() * 2.1 - 1;
    item.yspeed = Math.random() * 2.1 - 1;
    // item.position.normalize();
    items.push(item);
    scene.add( item );

    lineGeometry.vertices.push( item.position );

    testLineGeometry.vertices.push(new THREE.Vector3(item.position.x, item.position.y, 0));
    testLineGeometry.vertices.push(new THREE.Vector3(0, 0, 0));

    testLine = new THREE.Line( testLineGeometry, new THREE.LineBasicMaterial( {color: 0x000000} ) );
    lines.push(testLine);
    scene.add( testLine );

  }

  line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( {color: 0x000000} ) );
  // scene.add( line );

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  container.appendChild(renderer.domElement);
  //
}

//
function animate() {
  requestAnimationFrame( animate );
  render();
}
function render() {


items.forEach(circle => {
  circle.position.x += circle.xspeed;
  circle.position.y += circle.yspeed;

  if (circle.position.x > window.innerWidth / 2 || circle.position.x < -window.innerWidth / 2 ) {
    circle.xspeed *= -1;
  }

  if (circle.position.y > window.innerWidth / 2 || circle.position.y < -window.innerWidth / 2) {
    circle.yspeed *= -1;
  }
});

  testLine.geometry.verticesNeedUpdate = true;

  camera.position.x = 0;
  camera.position.z = 1000;

renderer.render( scene, camera );
}

My main concern is how I can ensure the correct vertices of testLine are updated during the render process.

Answer №1

testLineGeometry.vertices.push(new THREE.Vector3(item.position.x, item.position.y, 0));
It is intriguing to see why this approach is taken. The z-coordinate of the circles' positions is consistently set to 0, hence it would be more efficient to assign these positions directly as elements of the vertices array for the testLine.

I have revised your code:

  • Directly pushed circle positions into the vertices array of testLine:
    testLineGeometry.vertices.push(item.position);
  • Utilized the same center point;
  • Moved the instantiation of testLine outside of the for loop;
  • Opted for THREE.LineSegments() over THREE.Line(), considering that your testLine has double the amount of vertices compared to the circles.

var container;
var camera, scene, renderer, lines = [],
  items = [];

var numItems = 40;
var xspeed;
var yspeed;
var lineGeometry;
var testLineGeometry;

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(0xf7f7f7);
  var geometry = new THREE.CircleBufferGeometry(20, 20);
  lineGeometry = new THREE.Geometry();
  var testLineGeometry = new THREE.Geometry();
  var center = new THREE.Vector3();
  for (var i = 0; i < numItems; i++) {
    var item = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
      color: Math.random() * 0x000000
    }));
    item.position.x = (Math.random() * 20.1 - 1);
    item.position.y = (Math.random() * 20.1 - 1);
    item.xspeed = Math.random() * 2.1 - 1;
    item.yspeed = Math.random() * 2.1 - 1;
    // item.position.normalize();
    items.push(item);
    scene.add(item);

    lineGeometry.vertices.push(item.position);
    
    testLineGeometry.vertices.push(item.position);
    testLineGeometry.vertices.push(center);
  }

  testLine = new THREE.LineSegments(testLineGeometry, new THREE.LineBasicMaterial({
    color: 0x000000
  }));
  lines.push(testLine);
  scene.add(testLine);

  line = new THREE.Line(lineGeometry, new THREE.LineBasicMaterial({
    color: 0x000000
  }));
  // scene.add( line );

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);
  //
}

//
function animate() {
  requestAnimationFrame(animate);
  render();
}

function render() {


  items.forEach((circle, idx) => {
    circle.position.x += circle.xspeed;
    circle.position.y += circle.yspeed;

    if (circle.position.x > window.innerWidth / 2 || circle.position.x < -window.innerWidth / 2) {
      circle.xspeed *= -1;
    }

    if (circle.position.y > window.innerWidth / 2 || circle.position.y < -window.innerWidth / 2) {
      circle.yspeed *= -1;
    }
  });

  testLine.geometry.verticesNeedUpdate = true;

  camera.position.x = 0;
  camera.position.z = 1000;

  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>

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

Tips for connecting 2 Bootstrap 5 carousels

I currently have 2 Bootstrap 5 carousels (carousel-a & carousel-b) on the same page and I want them to be synchronized with each other. I believe this can be achieved using JavaScript, but I am not very familiar with it. Below is the structure of carousel- ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

Exclude mock files from webpack configuration in AngularClass/angular2-webpack-starter for production builds

I've encountered some obstacles while working with the AngularClass/angular2-webpack-starter framework, specifically in configuring its webpack settings. My goal is straightforward, yet I've been struggling to achieve it. In my project directory ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

Concentrate on Selecting Multiple Cells in ag-Grid (Similar to Excel's Click and Drag Feature)

Is there a way to click and drag the mouse to adjust the size of the focus box around specific cells in ag-Grid? This feature is very handy in Excel and I was wondering if it is available in ag-Grid or if there is a workaround. Any insights would be apprec ...

Is there a way to refresh angular bindings using data retrieved from a getUserMedia stream?

I'm currently using getUserMedia to capture an audio stream. The audio stream is only accessible within the getUserMedia callback function. However, I have encountered an issue where Angular fails to detect changes and update the bindings when I attem ...

Is there a way to iterate through documents in Mongoose using NodeJS?

Two collections are being used here - Let's call them the main and sub collections. The main collection is structured as follows: { "_id" : "xxxxx", "subId" : "1234" } The sub collection has a different structure: { "_id" : "1234", "name" : ...

Exploring the process of extracting a nested JSON value using Postman

I am currently facing an issue with parsing the json response from a post request, and then sending the parsed data to a put request. Here is the response body: { "createdBy": "student", "createdOn": "2019-06-18", "Id1": "0e8b9 ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

When validating an array in JavaScript, it is important to note that not all elements may be displayed. Only the last variable of each element will

I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's a ...

When scrolling, a new page loads seamlessly

Recently, I came across a website that has an interesting feature where new content is loaded automatically while scrolling, seamlessly appending to the existing page. What's more fascinating is that not only does the content change, but the URL also ...

How can the title of a link be hidden in a popup panel?

Seeking assistance for a popup panel issue. When you click on the black ffff button, a popup panel appears with the text ffff having a blue shadow in the top left corner that disappears when clicked. How can I remove this? Here's the link: <a class ...

Leverage the power of Signal R through React with aspnet/signalr integration

I found a helpful resource for incorporating SignalR into react, which you can check out here. However, it seems that the code provided does not align with current standards. The @aspnet/signalr-client has been marked as obsolete and now we are required t ...

The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question: const handleSubmit = async (e) => { e.preventDefault(); console.log(songLink) const newSong = { songName, songLink, userId }; const song = await dispatch(pos ...

Angular 14 - Issue with passing values through props - Error: Uncaught (in promise): InvalidCharacterError occurs when attempting to set attribute with 'setAttribute' method

I am a beginner with Angular and encountering an issue when trying to pass props from a parent component to a child component. The specific error I am facing is related to an invalid attribute name while using Angular version 14.2.5. core.mjs:7635 ERROR ...

.toggle function malfunctioning

Upon page load, I have a script that toggles the County menu. The goal is to hide the county menu if any country other than "United Kingdom" is selected on page load. If the user selects another country after the page has loaded, there is an issue where ...

What is the best way to iterate through array elements with AngularJS?

I am looking to showcase array values using the ng-repeat directive, and then call the getimage function with itemid and photoidlist in order to retrieve the image URL. The JSON data that I have is as follows: $scope.productslist = { "json": { "re ...

Utilize a dual-color gradient effect on separate words within the <li> element

I am attempting to display the fizz buzz function in an unordered list, with each word being a different color ('fizz'-- green, 'buzz'--blue) as shown here: https://i.sstatic.net/Yvdal.jpg I have successfully displayed "fizz" and "buz ...

No visibility of Mesh Groups in Three.JS ColladaLoader

When using Sketchup, creating components makes it easier to reuse geometry. For example, a car wheel can be designed as a component and then used multiple times for each wheel of the car. The challenge arises when trying to manipulate each reused componen ...