- Home /
Vector3.Lerp curving along three destinations
Hi, I'm working on a game in which the player can freeze time and place up to three destinations (stored in array) and then dash through them in sequence. I've got dash working but it seems to be curving through the from the starting position to the last destination rather than going from point to point. Any help would be appreciated!
void SetDestinations()
{
if (dashNumber < 3)
{
dashMarks[dashNumber].transform.position = dashDestination;
dashMarks[dashNumber].SetActive(true);
dashOrigin = dashMarks[dashNumber].transform.position;
dashNumber++;
}
}
void TriggerDashes()
{
dashNumber = 0;
foreach (GameObject gameObject in dashMarks)
{
if (dashMarks[dashNumber].transform.position != Vector3.zero)
{
StartCoroutine(LerpDash(dashMarks[dashNumber].transform.position, dashSpeed));
dashMarks[dashNumber].SetActive(false);
dashMarks[dashNumber].transform.position = Vector3.zero; //reset position to limit next dashes
dashNumber++;
}
}
}
IEnumerator LerpDash(Vector3 targetPosition, float duration) //still seems to be smoothing between points?
{
float time = 0;
while (time < duration)
{
transform.LookAt(targetPosition);
transform.position = Vector3.Lerp(transform.position, targetPosition, time / duration);
time += Time.deltaTime;
yield return null;
}
transform.position = targetPosition; //snapping
}
Answer by Namey5 · Jun 21, 2021 at 01:18 AM
The problem lies in that you are updating the position of the transform while also using it as the input parameter to the lerp - meaning the translation is no longer linear. To fix this, you just need to keep the inputs constant;
IEnumerator LerpDash(Vector3 targetPosition, float duration)
{
float time = 0;
Vector3 startPos = transform.position;
while (time < duration)
{
transform.LookAt(targetPosition);
transform.position = Vector3.Lerp(startPos, targetPosition, time / duration);
time += Time.deltaTime;
yield return null;
}
transform.position = targetPosition;
}
When I add the constraints, the player lerps straight to the final destination and disregards any previously placed destinations altogether.
I've tried setting the startPos outside of the coroutine but it has the same result.
That is because you are running all LerpDash instances at the same time (meaning only the last one will have an impact). You would need to either rejig the LerpDash function to include all points or make TriggerDashes a coroutine that yields upon each dash;
IEnumerator TriggerDashes()
{
dashNumber = 0;
foreach (GameObject gameObject in dashMarks)
{
if (dashMarks[dashNumber].transform.position != Vector3.zero)
{
yield return LerpDash (dashMarks[dashNumber].transform.position, dashSpeed);
dashMarks[dashNumber].SetActive(false);
dashMarks[dashNumber].transform.position = Vector3.zero; //reset position to limit next dashes
dashNumber++;
}
}
}
Thank you so much, it took a little tweaking but it's finally working as intended!