Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creates a flat mesh based on a spline, useful for roads.
//Produces a flat mesh based on a spline, useful for creating roads.
public class SplineMesh : MonoBehaviour
{
public static Mesh CreateSplineMesh(Vector3[] splinePoints, float[] widthPoints)
{
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[splinePoints.Length * 2];
//Create new vertices at both sides of the spline point
for (int i = 0; i < splinePoints.Length; i++)
{
if (i * 2 < vertices.Length - 1)
{
Vector3 leftDirection = Vector3.zero;
Vector3 rightDirection = Vector3.zero;
Vector3 heading = Vector3.zero;
if (i < splinePoints.Length - 1)
{
heading = splinePoints[i+1] - splinePoints[i];
}
else
{
heading = splinePoints[i] - splinePoints[i-1];
}
heading = heading / heading.magnitude;
leftDirection = Quaternion.Euler(0, -90, 0) * heading;
rightDirection = Quaternion.Euler(0, 90, 0) * heading;
vertices[i * 2] = splinePoints[i] + leftDirection * widthPoints[i];
vertices[i * 2 + 1] = splinePoints[i] + rightDirection * widthPoints[i];
}
}
//Calculate triangles based on created vertices
int[] triangles = new int[vertices.Length * 3];
bool oddTriangle = true;
for (int i = 0; i < vertices.Length; i++)
{
if (i + 2 < vertices.Length)
{
//Odd numbered triangles need to be reversed
if (oddTriangle)
{
triangles[i * 3] = i + 1;
triangles[i * 3 + 1] = i;
triangles[i * 3 + 2] = i + 2;
}
else
{
triangles[i * 3] = i;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = i + 2;
}
oddTriangle = !oddTriangle;
}
}
triangles[triangles.Length - 1] = vertices.Length - 1;
//Strectch UV over every normal
Vector2[] newUVs = new Vector2[vertices.Length];
for (int i = 0; i < newUVs.Length; i += 4)
{
if (i + 3 < newUVs.Length)
{
newUVs[i] = new Vector2(0, 1);
newUVs[i + 1] = new Vector2(0, 0);
newUVs[i + 2] = new Vector2(1, 1);
newUVs[i + 3] = new Vector2(1, 0);
}
}
mesh.RecalculateNormals();
mesh.RecalculateTangents();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = newUVs;
return mesh;
}
}
@turbohermit

This comment has been minimized.

Show comment
Hide comment
@turbohermit
Owner

turbohermit commented Jan 3, 2018

road

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment