I am trying to build a plane mesh of the brachistochrone curve in unity. But when i start the game some triangles attach to wrong position (see below). I am just into C# and unity and have no idea what i am doing wrong.
The long triangle going towards the screen shouldn’t be there.
And here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class terain : MonoBehaviour
{
Mesh mesh;
Vector3[] vertices;
int[] triangles;
public int ySize;
public int xSize = 2;
// some variables for the brachistochrone equation
public float increment = 1.0f;
public float distance = 1.0f;
public float height = 1.0f;
// Start is called before the first frame update
private void Awake()
{
Generate();
}
//generates mesh
private void Generate()
{
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Procedural Grid";
// the zSize is equal to pi / increment (+0.5 to add an extra index just to be sure)
int zSize = (int)(Mathf.PI / increment + 0.5f);
vertices = new Vector3[(xSize + 1) * (zSize + 1)];
float y = 1.0f;
//phi devines x and z
float phi = 0.0f;
int z = 0;
for (int i = 0; phi <= Mathf.PI; phi=phi+increment)
{
z = (int)(10 * 0.5f * distance * (phi - Mathf.Sin(phi)));
y = 10 * -0.5f * height * (1 - Mathf.Cos(phi));
for (int x = 0; x < xSize; i++, x++)
{
int yInt = (int)y;
vertices[i] = new Vector3(x, yInt, z);
}
}
// No idea what the rest of the code means
mesh.vertices = vertices;
z = 0;
int[] triangles = new int[xSize * zSize * 6];
for (int ti = 0, vi = 0; z < zSize; z++, vi++)
{
for (int x = 0; x < xSize; x++, ti += 6, vi++)
{
triangles[ti] = vi;
triangles[ti + 3] = triangles[ti + 2] = vi + 1;
triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
triangles[ti + 5] = vi + xSize + 2;
}
}
mesh.triangles = triangles;
MeshCollider meshc = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
meshc.sharedMesh = mesh;
}
}
Normally i would try to figure it out myself, but my time is limited because its for a school project. Somebody knows what i am doing wrong?