Triangulator

Author: runevision

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.

Note: This is a naive triangulation implementation. For more well-distributed triangles, consider using Delaunay triangulation, such as with the script here

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):

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.

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:

var tr:Triangulator = new Triangulator; tr.initTriangulator(verts2d); var triangles:int[] = tr.Triangulate;

and then assign the triangles array to mesh.triangles of your desired mesh object.