Creating polygon surfaces from points in THREE.js

I'm struggling to find the solution, even though I am working on the 3D Graphics course on Udacity that utilizes three.js. The task at hand is to create a 3D mesh and while I have successfully generated the vertices, I am facing difficulties with generating non-overlapping faces for them. Despite extensive searching online, I haven't been able to locate any helpful information regarding this issue. It's frustrating because I can't tell if the solution is incredibly simple or just not well-documented. The following code snippet illustrates my current roadblock:

function PolygonGeometry(sides) {
    var geo = new THREE.Geometry();

    // generate vertices
    for ( var pt = 0 ; pt < sides; pt++ )
    {
        // Add 90 degrees so we start at +Y axis, rotate counterclockwise around
        var angle = (Math.PI/2) + (pt / sides) * 2 * Math.PI;

        var x = Math.cos( angle );
        var y = Math.sin( angle );

        // YOUR CODE HERE
        //Save the vertex location - fill in the code
        geo.vertices.push( new THREE.Vector3(x, y, 0) );
    }
    // YOUR CODE HERE
    // Write the code to generate minimum number of faces for the polygon.


    // Return the geometry object
    return geo;
}

Although I understand the basic formula for determining the minimum number of faces (n-2), I am unable to implement it successfully without encountering face overlap issues. I prefer to work through challenges independently but would greatly appreciate any guidance or formula suggestions to point me in the right direction.

Answer №1

Streamline your triangulation process

When dealing with large polygons, manually adding faces can be a tedious task. Simplify the task by automating the face addition process to your Mesh using the triangulateShape method found in THREE.Shape.Utils. Here's how you can do it:

var vertices = [array of your vertices]
var holes = [];
var triangles, mesh;
var geometry = new THREE.Geometry();
var material = new THREE.MeshBasicMaterial();

geometry.vertices = vertices;

triangles = THREE.Shape.Utils.triangulateShape(vertices, holes);

for(var i = 0; i < triangles.length; i++) {
    geometry.faces.push(new THREE.Face3(triangles[i][0], triangles[i][1], triangles[i][2]));
}

mesh = new THREE.Mesh(geometry, material);

In this code snippet, ensure that the vertices represent your array of vertices, and optionally use the holes parameter to define any polygonal holes.

Important: Take caution as a self-intersecting polygon will result in an error. Verify that your vertices array accurately represents a valid, non-intersecting polygon.

Answer №2

When organizing vertices in a concave formation and moving counterclockwise, the connections follow a specific pattern. For instance, with 3 sides (triangle), you connect vertex 0 to 1 and then to 2. If there are 4 sides (quad), connect vertex 0 to 1 and then to 2 (forming the first triangle), followed by connecting vertex 0 to 2 and then to 3. This pattern continues as more sides are added - for a pentagon (5 sides), connect vertex 0 to 1 and then to 2 (first triangle), then vertex 0 to 2 and then to 3 (second triangle), and finally vertex 0 to 3 and then to 4. The sequence maintains this structure accordingly.

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

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

Receiving JSON dynamically (using socket.io) may result in parsing issues

I am currently working with JSON data that is correctly formatted at 100% accuracy. My issue arises when I execute the following code successfully: var data = {"datas":[{"matts":{"active":"1","status":"off"},"config":null,"adapters":[]}}]}; console.dir( ...

Using ServiceWorker with React and Typescript

If you are working on a javascript-based React project, adding a Service Worker is simply a matter of updating serviceWorker.unregister() to serviceWorker.register() in index.jsx. Here is an example project structure: - src |- index.jsx |- serviceWo ...

Receiving no communication from Express Router

Having trouble receiving a response from the server after making get/post requests. I've tried adjusting the order of functions in index.js without success. I also attempted to send a post request using Postman to localhost:8080/register, but the requ ...

Edit the contents within HTML strings without altering the HTML structure

If I have a string of HTML, it might look something like this... <h2>Header</h2><p>all the <span class="bright">content</span> here</p> I am interested in manipulating the string by reversing all the words. For example ...

Transforming the storage mechanism within Redux

I am looking to modify the overall state of Redux (commonly referred to as storage). Below is the code I have written: reducer export const user = (state = {}, action) => { console.log(4); console.log(action.type) console.log(action.payloa ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

How do you achieve the same effect as <Redirect to="/login" /> with the Navigate component in react-router-dom v6?

When utilizing react-router-dom v5, I had the following code snippet that would direct users to the login page if they weren't authenticated, or to the rest of the application if they were: !isAuthenticated ? ( <> ...

Error: The request does not have the 'Access-Control-Allow-Origin' header

As a beginner in post requests, I've been encountering an error when attempting to make a post request. Despite searching for solutions, the answers are too complex for me to grasp how to adjust my code to resolve it. var url = 'http://unturnedb ...

Set the return value of the mongoose function to a variable in node.js

As a newcomer to node js and mongoose, I have encountered the following code in my node js project. I am trying to store the mongoose return record userData in a variable user that is outside of the callback function. var user = null; User.findOne({$and: ...

After zooming, are mouse coordinates pointless?

Issue with Mouse Coordinates After Zooming I am facing a problem with obtaining accurate mouse coordinates after zooming in my code. I have included a JS fiddle link to showcase the issue. I am unsure if it is a bug in three.js or if my approach to drawin ...

Universal Navigation Search Component for Vue Router

Just starting out with Vue and frontend development. I'm attempting to create a universal navigation bar in Vue Router using bootstrap vue, complete with a search bar feature. However, because I have placed my navigation bar in App.vue, I am encount ...

Setting up Laravel Mix Vue.js source maps to display actual component code during debugging

My current setup includes Laravel 5.4 and Vue.js 2.6. I'm facing an issue with viewing the sourceMap of *.vue component files in the console. Here is how I've configured Laravel mix: let mix = require('laravel-mix'); mix.webpackConfig ...

Encountered an error with the POST request - TypeError: Unable to access the 'name' property as it is undefined

I'm currently facing some issues with using nodemailer to send emails. I believe I have everything set up correctly. I came across some posts mentioning deprecated code with the body parser, and I attempted their solutions...I think I've implemen ...

Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error: exportPageAsText(pageNumber: number): string { (async () => { const text = await this.pdfViewerService.getPageAsText(pageNumber); ...

Displaying a JSON object in a component's state through appending

I am currently working with a function that takes the state of an object as input and performs various operations on it. After these operations, I need to update the state accordingly and display it in JSON format. Here is the initial state: state= { ...

Using the OR condition in the ternary operator within ReactJS

Recently, I have started working on a ReactJS project focusing on menus. In this project, I have successfully implemented logic for the active menu feature. For instance, when a user is on page 2, the corresponding menu item will be highlighted as active. ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Setting up types for variables in Angular 2 componentsHere is an

I have a model that consists of multiple properties, and I aim to set all these properties with a default value of either empty or null. Here is an example of my Model: export class MyModel { name: string; jerseyNumber: number; etc... } In m ...

Calculating the sum of all textboxes with jQuery

I'm encountering an issue when trying to add the values of textboxes on blur call. Specifically, after entering a number in one of the textboxes, it throws NaN when attempting to sum up the values from other textboxes. Below is the code snippet causi ...