Skip to content

Instantly share code, notes, and snippets.

@ysalihtuncel
Created April 5, 2025 18:51
Show Gist options
  • Save ysalihtuncel/685fd874de45eecdc73754385f3b3d05 to your computer and use it in GitHub Desktop.
Save ysalihtuncel/685fd874de45eecdc73754385f3b3d05 to your computer and use it in GitHub Desktop.
Spline
using UnityEngine;
public class CarFollowSpline : MonoBehaviour
{
public SplineST spline;
public float speed = 0.2f;
private float t = 0f;
Vector3 initialPosition;
Vector3 initialRotation;
void OnEnable()
{
initialPosition = transform.position;
initialRotation = transform.eulerAngles;
}
void Update()
{
if (spline == null) return;
t += Time.deltaTime * speed;
t = Mathf.Clamp01(t); // 0-1 arası kalsın
Vector3 position = spline.GetPoint(t);
Vector3 direction = spline.GetTangent(t);
transform.position = position;
transform.rotation = Quaternion.LookRotation(direction);
}
[ContextMenu("Reset t")]
public void ResetT()
{
t = 0f;
transform.position = initialPosition;
transform.eulerAngles = initialRotation;
}
public void SetSpeed(float newSpeed)
{
speed = newSpeed;
}
}
using UnityEngine;
public class SplineST : MonoBehaviour
{
[Header("Spline Noktaları (Sıralı)")]
public Transform[] controlPoints;
public Vector3 GetPoint(float t)
{
int numSections = controlPoints.Length - 3;
if (numSections < 1)
{
Debug.LogWarning("Spline için en az 4 nokta gerekir.");
return Vector3.zero;
}
t = Mathf.Clamp01(t);
float scaledT = t * numSections;
int currPt = Mathf.FloorToInt(scaledT);
currPt = Mathf.Clamp(currPt, 0, numSections - 1);
float u = scaledT - currPt;
Vector3 a = controlPoints[currPt].position;
Vector3 b = controlPoints[currPt + 1].position;
Vector3 c = controlPoints[currPt + 2].position;
Vector3 d = controlPoints[currPt + 3].position;
return 0.5f * (
(-a + 3f * b - 3f * c + d) * (u * u * u)
+ (2f * a - 5f * b + 4f * c - d) * (u * u)
+ (-a + c) * u
+ 2f * b
);
}
public Vector3 GetTangent(float t)
{
float delta = 0.001f;
Vector3 p1 = GetPoint(t);
Vector3 p2 = GetPoint(t + delta);
return (p2 - p1).normalized;
}
private void OnDrawGizmos()
{
if (controlPoints == null || controlPoints.Length < 4) return;
Gizmos.color = Color.green;
Vector3 prevPoint = GetPoint(0);
for (float t = 0; t <= 1f; t += 0.01f)
{
Vector3 point = GetPoint(t);
Gizmos.DrawLine(prevPoint, point);
prevPoint = point;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment