- Home /
Question by
adamscamden2 · Feb 16, 2020 at 01:20 PM ·
c#meshprogramming
I have no Idea how to calculate the faces for my programily generated mesh,What is the easiest way I could calculate faces for my mesh
So I am making a programily generating cave program and I have all the vertices but I have no idea how to solve for the faces of my mesh. My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapGen : MonoBehaviour
{
Mesh mesh;
int[] triangles;
public int xSize = 20;
public int zSize = 20;
public int ySize = 20;
[Range(0f, 4.5f)]
public float SurfaceLevel = 3.5f;
Vector3[] interest;
Vector3 old = new Vector3(0, 0, 0);
public bool ShowAlg = false;
[Header("Slows down the scene veiw dramaticly when in play mode!")]
public bool ShowVert = true;
// Start is called before the first frame update
void Start()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
CreateShape();
SolveFaces();
UpdateMesh();
}
void CreateShape()
{
interest = new Vector3[(xSize + 1) * (zSize + 1) * (ySize + 1)];
float seed = Random.Range(0.2f, 0.5f);
Debug.Log(seed);
for (int x = 0; x <= ySize; x++)
{
for (int i = 0, y = 0; y <= zSize; y++)
{
for (int z = 0; z <= xSize; z++)
{
float ypn = (Mathf.PerlinNoise(x * seed, z * seed) * 2f);
float xpn = (Mathf.PerlinNoise(y * seed, z * seed) * 2f);
float zpn = (Mathf.PerlinNoise(x * seed, y * seed) * 2f);
if (ypn + xpn + zpn >= SurfaceLevel)
{
interest[i] = new Vector3(x, y, z);
}
i++;
}
}
}
}
void SolveFaces()
{
triangles = new int[xSize * ySize * zSize * 9];
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = interest;
mesh.triangles = triangles;
mesh.RecalculateNormals();
MeshCollider meshc = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
meshc.sharedMesh = mesh;
}
private void OnDrawGizmos()
{
if (interest == null)
return;
for (int i = 0; i < interest.Length; i++)
{
if (ShowVert == true)
{
Gizmos.color = new Color (0.286f, 0.486f, 0.812f);
Gizmos.DrawSphere(interest[i], 0.2f);
}
if(ShowAlg == true)
{
Gizmos.color = Color.green;
Gizmos.DrawLine(old, interest[i]);
old = interest[i];
}
}
}
}
This script is placed on a empty Game Object with a Mesh Filter, Renderer, and a collider. Note they do nothing without the faces. I have set it up so the face array goes on the triangles variable and missing part of the script should go in the SolveFaces() function. Thanks in advance.
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Morph along the 4th dimension 1 Answer
Drawing emojis with Unity's Dynamic Font 1 Answer
fps player controller using rigidbody without character controller? 2 Answers