I’m new to generating meshes at runtime and i tried to create a polygon from script. The Vertices are stored as Vector3 points. (im using this asset to draw the shape. )I’m calculating their average value to find a centre and my script creates triangles to connect it with the other vertices. So far, my script works but one triangle seems to be missing and i tried around but i cant figure out why or which one. It might be simple but i don’t see it. if anyone wants to help, I’d really appreciate it:)
private void CreateFloor()
{
if (pathCreator.bezierPath.IsClosed)
{
Vector3[] verts = new Vector3[path.NumPoints + 1]; //path.numpoints is the count of points of polygon
for (int i = 0; i < path.NumPoints - 1; i++)
{
verts[i] = path.GetPoint(i);
}
verts[path.NumPoints] = GetAverage(verts);
List<int> triangles = new List<int>();
//my uneducated guess on which triangle is missing, doesn't do anything:
triangles.Add(0); triangles.Add(verts.Length-2); triangles.Add(verts.Length-1);
//generate triangles:
for (int i = 0; i < verts.Length-1; i++)
{
triangles.Add(i);
triangles.Add(i + 1);
triangles.Add(path.NumPoints);
}
Debug.Log("triangles:" + triangles.Count + " points: "+path.NumPoints+"------"+"extra: 0, " + (verts.Length - 2) + ", " + path.NumPoints);
Mesh floormesh = new Mesh();
floormesh.SetVertices(verts);
floormesh.subMeshCount = 1;
floormesh.SetTriangles(triangles, 0);
floormesh.RecalculateNormals();
floormesh.RecalculateBounds();
//assign mesh;
if (floor == null)
{
floor = new GameObject("floor").AddComponent<MeshFilter>();
floor.gameObject.AddComponent<MeshRenderer>();
}
floor.mesh = floormesh;
}
}
public static Vector3 GetAverage(Vector3[] vectors)
{
Vector3 average = Vector3.zero;
for (int i = 0; i < vectors.Length; i++)
{
average += vectors[i];
}
return average / vectors.Length;
}