Hello, I would like to understand and create a simple script to make a sprite (in 2D only) follow a Unity spline over time.
I have some early code working but I am getting caught up with quaternions and rotation as the 2D sprite isn’t rotating and pointing forward where it should and to be honest this part is way over my head at this point.
I understand and have successfully used Unity’s built-in Spline Animate component but I would like to achieve a simplified implementation that only does this singular thing well and is something that I can understand and build off of in future.
Thank you kindly in advance for any guidance you could provide.
Edit: Here is the code I have (partially) working so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Splines;
public class splineMoveWorks : MonoBehaviour
{
[SerializeField]
private SplineContainer splineContainer;
public float Speed = 1;
private void Update(){
var localPoint = splineContainer.transform.InverseTransformPoint(transform.position);
SplineUtility.GetNearestPoint(splineContainer.Spline, localPoint, out var nearest, out var ratio, 10, 10);
var tangent = SplineUtility.EvaluateTangent(splineContainer.Spline, ratio);
var rotation = Quaternion.LookRotation(tangent);
transform.rotation = rotation;
Debug.Log(rotation);
var globalNearest = splineContainer.transform.TransformPoint(nearest);
var perpendicular = Vector3.Cross(tangent, Vector3.up);
var position = globalNearest + perpendicular.normalized;
transform.position = position;
transform.Translate(Vector3.forward * Speed * Time.deltaTime, Space.Self);
}
}