How to Use a Function to Generate Triangular Shapes in Three.js Using an Array of Vertices

I am diving into the world of JS and THREE.js with the goal of creating a function that performs the following tasks:

  • Combine every 3 values to generate a new vertex,
  • Group every 3 vertices to create a new THREE.Triangle(ta, tb, tc);
  • Keep track of all these triangles in an Array
  • Determine the total area of each Triangle using Triangle.getArea()

Here is the progress I have made:

// Initialize an empty Array to hold all the Triangles
   var triangles = [];

//  pos is an array that contains all the points/vertices -- with a total of 72 values 
   var pos = threeMesh1.geometry.attributes.position;
  
   function makeTriangle(ta, tb, tc){
   
    for (i = 0; i < pos.count; i++) {
// For *every 3 instances*, assign the values to ta, tb, tc,
    ta = new THREE.Vector3( pos.getX(i), pos.getY(i), pos.getZ(i)); //posX(0),posY(0),posZ(0)
    tb = new THREE.Vector3( pos.getX(i+=1), pos.getY(i+=1), pos.getZ(i+=1) );//posX(1),posY(1),posZ(1)
    tc = new THREE.Vector3( pos.getX(i+=2), pos.getY(i+=2), pos.getZ(i+=2));//posX(2),posY(2),posZ(2)
   //the next set should be i =(3,4,5) (6,7,8) (9,10,11), etc.

// Create a new triangle Object
    tri = new THREE.Triangle(ta, tb, tc);
 

// Add new triangle to the original "triangles" array
    triangles.push(tri);
    
   }
}
makeTriangle(triangles);  
console.log(triangles); // returns [Triangle, Triangle, Triangle]

How can I make the every 3 instances inside the for loop function correctly? Currently, instead of 0,1,2 / 3,4,5 / 6,7,8, it is giving 0,3,6,9, etc.

Answer №1

I found a helpful solution on the three.js Discourse forum here. Hopefully, this information can assist others as well!

const triangleArray = [];
const positions = mesh.geometry.attributes.position;

const pointA = new THREE.Vector3();
const pointB = new THREE.Vector3();
const pointC = new THREE.Vector3();

const totalFaces = positions.count / 3;

function createTriangle() {
for (let i = 0; i < totalFaces; i++){
const triangle = new THREE.Triangle();
  pointA.fromBufferAttribute(positions, i * 3 + 0);
  pointB.fromBufferAttribute(positions, i * 3 + 1);
  pointC.fromBufferAttribute(positions, i * 3 + 2);
  triangle.set(pointA, pointB, pointC);

  const area = triangle.getArea();

  // Add triangle to array
    triangleArray.push(triangle);
    console.log(area);
    }   
}  
createTriangle(triangleArray);  
console.log(triangleArray); // output: [Triangle, Triangle, Triangle]

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

Validation in AngularJS - Setting minimum length for textarea using ng-minlength

I am currently tackling a project that heavily relies on AngularJS for the front-end. Here's what I am dealing with: The validation requirement I am aiming for is as follows: The Next button should remain disabled unless the reason provided is at le ...

Transferring identification data between views within an application (AngularJS, NodeJs, HTML)

I'm working on an HTML page that lists users from MongoDB. The page allows for deleting and updating users. I am encountering an issue with the update button - I want a new HTML page to appear with a form when the button is clicked, capturing the user ...

What is the most effective method for embedding a Kotlin program into a website?

I have created a combat simulation tool in Kotlin for an online gaming community. Users can input the combat levels of two players, choose the number of duels to simulate, and then initiate the simulation which will provide win percentages and other stats. ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...

What is the purpose of storing JSON data as a string within another JSON object?

Screenshot of developer tools While exploring the local storage on my visit to YouTube, I came across some very peculiar-looking JSON data. { creation: 1638112285935, data: "{\"quality\":1080,\"previousQuality&bs ...

This function is functional with jquery version 1.4.2 but encounters issues with jquery version 1.9.1

I have encountered an issue with a script that submits data to my database. The script worked perfectly on version 1.4.2, but the template I am using now requires version 1.9.1, so I updated my site accordingly. However, after the update, I am facing an er ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

`Look up values from specified key names`

Consider the following JSON data: const information = { "item1":1, "item2":20, "item3":123, "item4":[{"a":"apple","b":"ball"}], "item5":1211 } In ...

React Native encountered an error: `undefined` is not an object

Encountering the commonly known error message "undefined is not an object" when attempting to call this.refs in the navigationOptions context. Let me clarify with some code: static navigationOptions = ({ navigation, screenProps }) => ({ heade ...

Using Laravel 8 to create connected dropdown menus with the power of Ajax

Struggling with setting up a dependent dropdown menu in Laravel 8 using Ajax. The first dropdown works fine, but the next two don't display any options. Being new to Laravel, I'm having trouble pinpointing the problem areas. Seeking assistance to ...

Using a dynamic HTML interface, select from a vast array of over 50,000 values by leveraging the power

I am working on a project that includes a multiselect option with over 50,000 records. We are using AJAX to fetch data from the server based on user searches, which works fine. However, when a user tries to select all records by clicking the "check all" ...

Ways to eliminate empty values from an array in JavaScript

I need help deleting any null elements from my array [ [ null, [ [Array], [Array] ] ] ] I am looking to restructure it as [ [[Array],[Array]], [[Array],[Array]], [[Array],[Array]] ] If there are any undefined/null objects like : [ [[Array],[]], [[A ...

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...

Interactive JQuery calendar

Can anybody assist me with this issue? I am seeing question marks in the graphic and I'm not sure why. I remember encountering these symbols before and I believe it has something to do with charset. Currently, I am using: <meta http-equiv="Content ...

Conceal YouTube upon opening any model or light box

I have a YouTube video in the center of my page, and when I click on any link from the side navigation, a lightbox appears. However, in IE, the lightbox is behind the YouTube video. I have tried setting the Z-index, but it doesn't seem to work. Is the ...

Run a script on an ajax requested page prior to the page being loaded

My website navigation utilizes AJAX for seamless transitions between pages. Specifically, I have two pages: index.html and profile.html. The structure of both pages is as follows: <html> <head> <script src="script1.js" type="text/javascript ...

Daniel Opitz explores the best placement for DataTables within the slim4 framework

After purchasing Daniel Opitz's eBooks, I found myself on page 226 trying to implement data tables in my project. The books mention: DataTables Setup DataTables.net is a very flexible table plug-in for jQuery. You have to setup jQuery for Webpack firs ...

Transforming a Blob document into JSON format

I am attempting to convert a blob file into JSON format in order to transmit it via AJAX requests. Despite my efforts with the code below, I have not been successful in achieving this task. When I attempt to parse the JSONified file, I end up with a comp ...

The Jquery flot plugin is failing to plot the graph accurately based on the specified date

I am currently working on plotting a graph using the jquery flot plugin with JSON data. Here is what I need to do: Upon page load, make an AJAX call to receive JSON data from the server. From the received JSON, add 'x' and & ...

Executing JavaScript code in the Selenium IDE

I'm having trouble figuring out how to execute JavaScript within the Selenium IDE. The objective is to enter text into an input field, with a backend setup that verifies the current time in the input field for testing purposes: Here's the input f ...