using System.Collections; using System.Collections.Generic; using UnityEngine; public class trackGen : MonoBehaviour { public int sectionNum = 20; public float minWidth = 5; public float MaxWidth = 10; public float sectionLenth = 5; public float noiseOffset; [Range(0,10)] public float curveyFactor = 1; public MeshFilter meshFilter; [System.NonSerialized] public List newVerts = new List(); [System.NonSerialized] public List newTris = new List(); MeshCollider meshCollider; public void GenerateTrack() { Mesh mesh = new Mesh(); meshCollider = GetComponent(); meshFilter.mesh = mesh; mesh.Clear(); newVerts.Clear(); newTris.Clear(); Vector3 pos = Vector3.zero; Vector3 lastPos = Vector3.zero; float initialOffset = (Mathf.PerlinNoise(0, 0 * 0.1f) * 15) + (Mathf.PerlinNoise(0, 0 * 0.05f) * 60); float roadWidth = 10; float lastRoadWidth = 10; meshCollider.sharedMesh = mesh; for (int i = 0; i < sectionNum; i++) { pos = new Vector3((Mathf.PerlinNoise( noiseOffset, i * 0.1f) * 15) + (Mathf.PerlinNoise(noiseOffset, i * 0.05f) * 60) - initialOffset, 0, sectionLenth * i); roadWidth = Mathf.PerlinNoise(i * 0.2f, noiseOffset) * (MaxWidth-minWidth) + minWidth; // roadWidth = 10; addSection((pos.x) * curveyFactor - roadWidth, (pos.x) * curveyFactor + roadWidth,( lastPos.x) * curveyFactor - lastRoadWidth,( lastPos.x) * curveyFactor + lastRoadWidth, pos.z); lastRoadWidth = roadWidth; lastPos = pos; } mesh.vertices = newVerts.ToArray(); mesh.triangles = newTris.ToArray(); mesh.RecalculateNormals(); } void addSection(float frontleft, float frontright, float backleft, float backright,float z) { AddQuad(new Vector3(frontleft, 0, 5 + z), new Vector3(frontright, 0, 5 + z), new Vector3(backleft, 0, 0 + z), new Vector3(backright, 0, 0 + z)); AddQuad(new Vector3(backleft,5, 0 + z), new Vector3(frontleft, 5, 5 + z), new Vector3(backleft, 0, 0 + z), new Vector3(frontleft, 0, 5 + z)); AddQuad( new Vector3(backright, 0, 0 + z), new Vector3(frontright, 0, 5 + z), new Vector3(backright, 5, 0 + z), new Vector3(frontright, 5, 5 + z)); } // quad orientation vv //------------// // A B // // / // // / // // / // // C/ D // //------------// void AddQuad(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { AddTri(a, b, c); AddTri(b, d, c); } void AddTri(Vector3 a, Vector3 b, Vector3 c) { int vertsLength = newVerts.Count; newVerts.Add(a); newVerts.Add(b); newVerts.Add(c); newTris.Add(vertsLength + 0); newTris.Add(vertsLength + 1); newTris.Add(vertsLength + 2); } // Update is called once per frame void Update() { } }