Move First Person Character Controller Along a Spline

Hi everyone, I haven’t worked in Unity in a few years and am just getting into using the new Spline tool for the first time. I’ve set up a spline and laid out a path, etc. and now I’m needing to move a first person character controller along the spline using two particular scenarios, via keyboard input and also through input via connected Arduinos. The first way, the simplest way, using arrow keys (forward/backward) to increment/decrement the Path Position. Two, more complicated, but ultimately the way I actually need to do it is to move the camera dynamically along the path using an ever changing range of values, fed by an arduino connected to a tachometer on a stationary bike, 0 to 100 for instance, to simulate speed. The main thing I really need to solve in the immediate short term is linking the character controller to the spline and using arrow keys to move forward/backward along the spline path.

I know this is probably a pretty big question, but if anyone could just point me in the right direction, or if you have particular examples that you’ve come across that address these questions I would appreciate the help immensely! Thank you!

You could use Spline.Evaluate(Vector3 normalizedLength) to get the position and rotation on the spline.

Here’s an example:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Splines;

public class SplineMoving : MonoBehaviour
{
    [SerializeField] private SplineContainer spline;
    [SerializeField] private float maxSpeed = 3f;

    private float currentPos;

    private void Update()
    {
        UpdatePosOnSpline();
    }

    private void UpdatePosOnSpline()
    {
        var splineLength = spline.Spline.GetLength();
        var currentSpeed = GetMoveSpeed();
        // make sure on spline
        currentPos = Mathf.Clamp(currentPos + currentSpeed * Time.deltaTime, 0f, splineLength);
        // most important part: evaluate currentPos on spline
        var normalizedPos = currentPos / splineLength;
        spline.Spline.Evaluate(normalizedPos, out var pos, out var dir, out var up);
        transform.SetPositionAndRotation(pos, Quaternion.LookRotation(dir));
    }

    private float GetMoveSpeed()
    {
        // put your evaluating logic here (keyboard or arduino)
        return Input.GetAxis("Vertical") * maxSpeed;
    }
}
1 Like