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?
