I want to make my program generate a 3D graph of a formula within certain boundaries and a certain resolution. The problem with the code is that when I run it, the mesh has strange jagged edges and the triangles aren’t connecting properly making the mesh render very strangely(rendering on both sides).
Here is the code(C#):
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CustomGraph : MonoBehaviour {
string formula;
List<Vector3>verts;//Stores the list of vertices for the mesh
List<int>tris;//Stores the list of triangles for the mesh
List<Vector2> uvs;//Stores the list of uvs for the mesh
MeshFilter graphMesh = null;
void Start()
{
verts = new List<Vector3> ();
tris = new List<int> ();
uvs = new List<Vector2> ();
graphMesh = gameObject.GetComponent<MeshFilter> ();
if(graphMesh == null)
{
Debug.LogError("Graph does not have MeshFilter");
}
GenerateGraph(0,10,1f,"x");
}
void GenerateGraph(int start, int end, float res, string form)
{
ShuntingYard (form);
CalculateVerts (start, end, res);
CalculateTris (end-start);
UpdateGraph ();
}
void ShuntingYard(string form)
{
//Does whatever it does and saves it to the variable 'formula'
//Isn't needed for testing
}
void CalculateVerts(int start, int end, float res)
{
verts.Clear ();
for(float z = start; z <= end; z += res)
{
for(float x = start; x <= end; x += res)
{
Vector3 current_point = new Vector3();
current_point.x = x;
current_point.z = z;
current_point.y = CalculateY(x,z);
verts.Add (current_point);
uvs.Add (new Vector2(x,z));
}
}
}
float CalculateY(float x, float z)
{
//Calculates y using the ShuntingYard algorithm and returns the value
//For testing, the formula will be manually input
return x;
}
void CalculateTris(int width)
{
tris.Clear ();
for(int index =0; index < verts.Count-width; index++)
{
if(index == 0)
{
tris.Add(index);
tris.Add(index+1);
tris.Add (index+width);
}
else if(index % width == 0)
{
tris.Add(index);
tris.Add(index+1);
tris.Add (index+width);
}
else if((index + 1) % width == 0)
{
tris.Add(index);
tris.Add(index + width);
tris.Add (index + width - 1);
}
else
{
tris.Add(index);
tris.Add(index + width);
tris.Add (index + width - 1);
tris.Add(index);
tris.Add(index+1);
tris.Add (index+width);
}
}
}
void UpdateGraph()
{
Mesh finalgraph = new Mesh ();
finalgraph.vertices = verts.ToArray ();
finalgraph.triangles = tris.ToArray ();
finalgraph.uv = uvs.ToArray ();
finalgraph.RecalculateBounds ();
finalgraph.RecalculateNormals ();
graphMesh.mesh.Clear ();
graphMesh.mesh = finalgraph;
}
}
I’ve been messing around with the CalculateTris() method and that seems to be the problem, but I just can’t figure out what it is.
Please let me know if there are any clarifications that are needed. Thanks!