'm trying to make a script that creates a random 2d polygon from triangles, but the code I’m currently using only results in a mess of angles and crossing lines. I’ve tried to make the code so that it picks points around the centre of the shape, and ordering the angles so that none should cross, but they do anyway.
This is the kind of thing I want it to look like (minus the lines that point to the centre):

And this is what it actually looks like:
public class ShapeMaker : MonoBehaviour {
public Vector3[] vertices = new Vector3[8];
public Vector2[] shapeUV = new Vector2[8];
public List<float> angles = new List<float>();
public List<float> magnitudes = new List<float>();
int[] tris = new int[9];
void Start()
{
generateShape();
Mesh mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
mesh.vertices = vertices;
mesh.uv = shapeUV;
mesh.triangles = tris;
}
public void generateShape()
{
//Generate Angles
for (int j = 0; j < vertices.Length; j++)
{
float direction = Random.Range(-2f, 2f);
angles.Add(direction);
}
angles.Sort();
//Generate Magnitudes
for (int j = 0; j < vertices.Length; j++)
{
float magnitude = Random.Range(1f, 3f);
magnitudes.Add(magnitude);
}
//Combining into Vectors
int i = 0;
foreach(float direction in angles)
{
float magnitude = magnitudes[i];
float cx = magnitude * Mathf.Cos(direction);
float cy = magnitude * Mathf.Sin(direction);
vertices[i] = new Vector3(cx, cy, 0);
shapeUV[i] = new Vector2(cx, cy);
tris[i] = i;
i++;
}
GetComponent<PolygonCollider2D>().pathCount = 1;
GetComponent<PolygonCollider2D>().SetPath(0, shapeUV);
}
}
