Last active
July 5, 2023 16:48
-
-
Save ertanturan/4a54828715a12c609de6488151c20568 to your computer and use it in GitHub Desktop.
Basic/Primitive Curve maker and viewer for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using Random = UnityEngine.Random; | |
[Serializable] | |
public class Curve | |
{ | |
public Vector3[] points; | |
public int generateCount; | |
public float tunnelLength = 50f; | |
public float tunnelWidth = 10f; | |
public float tunnelHeight = 5f; | |
public int resolution = 500; | |
public void GenerateBezierPoints() | |
{ | |
var stepLength = tunnelLength / generateCount; | |
points = new Vector3[generateCount]; | |
var p0 = new Vector3( | |
Random.Range(-tunnelWidth / 2f, tunnelWidth / 2f), | |
Random.Range(-tunnelHeight / 2f, tunnelHeight / 2f), | |
Random.Range(0, tunnelLength / 2f) | |
); | |
p0.z = Random.Range(0f, stepLength); | |
points[0] = p0; | |
for (var i = 1; i < generateCount - 1; i++) | |
{ | |
var point = new Vector3( | |
p0.x + Random.Range(-tunnelWidth / 2f, tunnelWidth / 2f), | |
p0.y + Random.Range(-tunnelHeight / 2f, tunnelHeight / 2f), | |
Random.Range(stepLength * i, stepLength * (i + 1)) | |
); | |
points[i] = point; | |
} | |
points[generateCount - 1] = new Vector3( | |
p0.x + Random.Range(0, tunnelWidth), | |
p0.y + Random.Range(0, tunnelHeight), | |
tunnelLength | |
); | |
} | |
public Vector3 CalculatePointOnTheCurve(float t) | |
{ | |
var count = points.Length; | |
var tempControlPoints = new List<Vector3>(points); | |
for (var level = 0; level < count; level++) | |
for (var i = 0; i < count - level - 1; i++) | |
tempControlPoints[i] = Vector3.Lerp(tempControlPoints[i], tempControlPoints[i + 1], t); | |
return tempControlPoints[0]; | |
} | |
public void DrawGizmos() | |
{ | |
if (points == null || points.Length == 0) return; | |
Gizmos.color = Color.white; | |
var previousPoint = points[0]; | |
for (var i = 1; i <= resolution; i++) | |
{ | |
var t = i / (float)resolution; | |
var pointOnCurve = CalculatePointOnTheCurve(t); | |
Gizmos.DrawLine(previousPoint, pointOnCurve); | |
previousPoint = pointOnCurve; | |
} | |
} | |
public void DrawHandles() | |
{ | |
// draw handles ? | |
Gizmos.color = Color.red; | |
for (var i = 0; i < points.Length - 3; i++) | |
{ | |
var p0 = points[i]; | |
var p1 = points[i + 1]; | |
var p2 = points[i + 2]; | |
var p3 = points[i + 3]; | |
Gizmos.DrawLine(p0, p1); | |
Gizmos.DrawLine(p2, p3); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment