using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof(MeshFilter), typeof(MeshRenderer))]
public class ProceduralGrid : MonoBehaviour
{
Mesh mesh;
Vector3[] vertices;
int[] triangles;
public float cellSize = 1.0f;
public Vector3 gridOffset;
public int gridSize;
private void Awake()
{
//get mesh
mesh = GetComponent<MeshFilter>().mesh;
}
void Start()
{
ContinousGridMesh();
UpdateMesh();
}
void DiscreteGridMesh()
{
vertices = new Vector3[4*gridSize*gridSize];
triangles = new int[6*gridSize*gridSize];
float vertexOffset = cellSize * 0.5f;
int v = 0;
int t = 0;
//create vertex grid and triangle
//cell을 하나하나 씩 그려준다고 생각하면 된다.
for(int x=0; x<gridSize; x++)
{
for(int y=0; y<gridSize; y++)
{
Vector3 cellOffset = new Vector3(cellSize * x, 0, cellSize * y);
vertices[v] = new Vector3(-vertexOffset, x+y, -vertexOffset) + cellOffset + gridOffset;
vertices[v+1] = new Vector3(-vertexOffset, x+y, vertexOffset) + cellOffset + gridOffset;
vertices[v+2] = new Vector3(vertexOffset, x+y, -vertexOffset) + cellOffset + gridOffset;
vertices[v+3] = new Vector3(vertexOffset, x+y, vertexOffset) + cellOffset + gridOffset;
triangles[t] = v;
triangles[t + 1] = triangles[t+4] = v + 1;
triangles[t + 2] = triangles[t+3] = v + 2;
triangles[t + 5] = v + 3;
v += 4;
t += 6;
}
}
}
void ContinousGridMesh()
{
vertices = new Vector3[(gridSize + 1) * (gridSize + 1)];
triangles = new int[6 * gridSize * gridSize];
float vertexOffset = cellSize * 0.5f;
int v = 0;
int t = 0;
//create vertex grid
//연결된 vertices를 구하기 때문에 한 번에 구함
for (int x = 0; x <= gridSize; x++)
{
for (int y = 0; y <= gridSize; y++)
{
vertices[v] = new Vector3(((x * cellSize) - vertexOffset), (x+y)*0.2f, ((y*cellSize)-vertexOffset));
v++;
}
}
//reset v
v = 0;
//setting each cell's triangle
//vertices의 순서가 전체적으로 순차적으로 진행되기 때문에
//cell의 윗 부분은 gridSize+1을 더해준 순서로 구해진.
for(int x=0; x<gridSize; x++)
{
for(int y=0; y< gridSize; y++)
{
triangles[t] = v;
triangles[t + 1] = triangles[t + 4] = v + 1;
triangles[t + 2] = triangles[t + 3] = v + (gridSize+1);
triangles[t + 5] = v + (gridSize+1)+1;
v++;
t += 6;
}
v++;
}
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
}