Triangulator - Unity
From http://wiki.unity3d.com/index.php?title=Triangulator
Description
This script can be used to split a 2D polygon into triangles. The algorithm supports concave polygons, but not polygons with holes, or multiple polygons at once. Usage
Create a new Triangulator object with a array of Vector2 points as the constructor parameter. Then get the indices by calling the Triangulate method on the Triangulator. You can now use the points and the indices to construct a mesh. Example use (attach this script to a game object):
using UnityEngine;
public class PolygonTester : MonoBehaviour {
void Start () {
// Create Vector2 vertices
Vector2[] vertices2D = new Vector2[] {
new Vector2(0,0),
new Vector2(0,50),
new Vector2(50,50),
new Vector2(50,100),
new Vector2(0,100),
new Vector2(0,150),
new Vector2(150,150),
new Vector2(150,100),
new Vector2(100,100),
new Vector2(100,50),
new Vector2(150,50),
new Vector2(150,0),
};
// Use the triangulator to get indices for creating triangles
Triangulator tr = new Triangulator(vertices2D);
int[] indices = tr.Triangulate();
// Create the Vector3 vertices
Vector3[] vertices = new Vector3[vertices2D.Length];
for (int i=0; i<vertices.Length; i++) {
vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
}
// Create the mesh
Mesh msh = new Mesh();
msh.vertices = vertices;
msh.triangles = indices;
msh.RecalculateNormals();
msh.RecalculateBounds();
// Set up game object with mesh;
gameObject.AddComponent(typeof(MeshRenderer));
MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
filter.mesh = msh;
}
}Troubleshooting
If you can't see a polygon created with this utility, remember to check if the polygon is facing the opposite direction. If it is, you can change that by constructing your mesh with the vertex indices in reverse order. C#- Triangulator.cs
Javascript Triangulator Code
The steps for using this triangulation code are the same as for the c sharp example. You just need to create a Triangulator object like this:
and then assign the triangles array to mesh.triangles of your desired mesh object.
javascript - Triangulator.js
Last updated
Was this helpful?