I'm visualising GPS data provided from the cars in races in Formula 1, and am attempting to animate their position on a path. The Formula 1 API provides vector coordinates and timestamps, but the timestamps are varied: they're updated approximately between 100 and 400 milliseconds:
timestamp x y z
2023-03-19 18:23:39.562 -1396 503 118
2023-03-19 18:23:39.842 -1443 630 118
2023-03-19 18:23:40.142 -1531 868 117
2023-03-19 18:23:40.342 -1589 1028 117
2023-03-19 18:23:40.501 -1636 1157 117
2023-03-19 18:23:40.842 -1772 1527 117
2023-03-19 18:23:41.101 -1813 1640 117
2023-03-19 18:23:41.361 -1932 1964 117
2023-03-19 18:23:41.782 -2015 2190 117
2023-03-19 18:23:42.002 -2080 2368 117
...
When visualised the data points look like this:
I'm using a coroutine to Lerp between the vectors and updating on the time delta, but because the gaps are varied, it creates quite a jerky animation:
My coroutine looks like this (with thanks to @derHugo for this answer):
private IEnumerator AnimationRoutine()
{
if (alreadyAnimating) yield break;
alreadyAnimating = true;
var lastSample = _samples[0];
Car.transform.position = lastSample.Position;
yield return null;
for (var i = 1; i < _samples.Count; i++)
{
var lastPosition = lastSample.Position;
var currentSample = _samples[i];
var targetPosition = currentSample.Position;
var duration = currentSample.TimeDelta;
var timePassed = 0f;
while (timePassed < duration)
{
var factor = timePassed / duration;
Car.transform.position = Vector3.Lerp(lastPosition, targetPosition, factor);
yield return null;
timePassed += Time.deltaTime;
}
Car.transform.position = targetPosition;
lastSample = currentSample;
}
alreadyAnimating = false;
}
Is there a way I can maintain the time data I have but interpolate the transitions between points so they look smoother?