Camera System | Interpolate Animation RESOLVED

I’d like to feed a camera animation in the animator a float value between 0 and 1. The float value being the closest point on a line relative to the position of the moving character.

Here’s the script:

public class CameraSystemX : MonoBehaviour
{
    public Transform Hero;
    Vector3 playerPos;

    public string AnimatorParameter = "Interpolation";
    public float InterpolationSpeed = 3;
    float CamInterpolation;
    Animator CameraAnimator;

    public GameObject[] Positions;
    Vector3[] linePositions;

    float totalDistance;
    float closestDistance;
    float closestPoint;

    Vector3 startPos;
    Vector3 endPos;
    Vector3 lineDir;
    Vector3 playerDir;
    float lineLength;
    float t;
    Vector3 closestPointOnLine;
    float distance;


    private void Start()
    {
        CameraAnimator = GetComponent<Animator>();
        int HowMany = Positions.Length;
        linePositions = new Vector3[HowMany];

        for (int i = 0; i < linePositions.Length; i++)
        {
            linePositions[i] = Positions[i].transform.position;
        }
    }

    private void Update()
    {
        playerPos = new Vector3(Hero.position.x, 0, Hero.position.z);
        CamInterpolation = GetClosestPointOnLine();

        CameraAnimator.SetFloat(AnimatorParameter, CamInterpolation);
    }

    public float GetClosestPointOnLine()
    {
        totalDistance = 0f;
        closestDistance = float.MaxValue;
        closestPoint = 0f;

        for (int i = 0; i < linePositions.Length - 1; i++)
        {
            startPos = linePositions[i];
            endPos = linePositions[i + 1];
            lineDir = endPos - startPos;
            playerDir = playerPos - startPos;
            lineLength = lineDir.magnitude;
            t = Vector3.Dot(playerDir, lineDir) / (lineLength * lineLength);
            t = Mathf.Clamp01(t);
            closestPointOnLine = startPos + lineDir * t;
            distance = (playerPos - closestPointOnLine).magnitude;

            if (distance < closestDistance)
            {
                closestDistance = distance;
                closestPoint = totalDistance + t * lineLength;
            }
            totalDistance += lineLength;
        }
        return closestPoint / totalDistance;
    }
}

And here’s the problem (I think), could be something else or all of it.


So if the character crosses the second position along the line at either side of the path he’ll be further away or closer to both the first position and the third position. You see the green line, I think that causes the float value to skip ahead. I have consulted the AI gods about this and they don’t seem to know what to do. Someone who knows of a good way of doing this or fixing the code I posted?

Camera stuff is pretty tricky… you may wish to consider using Cinemachine from the Unity Package Manager.

There’s even a dedicated forum: Unity Engine - Unity Discussions

Beyond that, it’s probably best to simplify your setup and debug the problem. Here’s how:

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

I don’t think Cinemachine can interpolate an animation by looking at how close/far the character is along a path. I do think the cinemachine path object might be preferable to a series of empties. It creates a Bezier curve which would smooth out the angle when the character crosses the points. And you could in theory add more points which might remove the skip because of how small the distance change is illustrated in the picture. Especially with a delay applied to the float, like a MathF.Lerp before it’s sent to the Animator.

But I have no idea of how to do it with a cinememachine path, I don’t even know if my approach in the code above is any good. Shouldn’t it be possible to check the entire path and not in between points only. It’s sort of working right now, it’s just laggy when he crosses the points which suggests it might be something that could just be changed in the GetClosestPointOnLine function. What would you change in this function? Maybe since this is called in update it’s looping through the positions too often?

public float GetClosestPointOnLine()
    {
        totalDistance = 0f;
        closestDistance = float.MaxValue;
        closestPoint = 0f;
        for (int i = 0; i < linePositions.Length - 1; i++)
        {
            startPos = linePositions[i];
            endPos = linePositions[i + 1];
            lineDir = endPos - startPos;
            playerDir = playerPos - startPos;
            lineLength = lineDir.magnitude;
            t = Vector3.Dot(playerDir, lineDir) / (lineLength * lineLength);
            t = Mathf.Clamp01(t);
            closestPointOnLine = startPos + lineDir * t;
            distance = (playerPos - closestPointOnLine).magnitude;
            if (distance < closestDistance)
            {
                closestDistance = distance;
                closestPoint = totalDistance + t * lineLength;
            }
            totalDistance += lineLength;
        }
        return closestPoint / totalDistance;
    }

EDIT: The issue was the “resolution” of the line, you need more points a lot more points. You create them with a function that converts the line to a curved spline. So the 3 points in the picture turns into a 120 point curved line instead. With a slight delay to the interpolation, 0.1 second delay the jerkiness disappears.