I am having a strange issue when using a Vector3.Lerp inside a coroutine and it makes no sense because I have many Coroutines in my game and they are all working fine.
WHAT I AM TRYING TO ACHIEVE
I am simply trying to move an object from a starting height to a final height with a coroutine called InVolo() and a simple Vector3.Lerp to change the position of the object.
MY CODE
float elapsedTime = 0f;
while (elapsedTime < TempoSalita)
{
transform.position = Vector3.Lerp(transform.position,
new Vector3(transform.position.x, maxHight, transform.position.z), (elapsedTime / TempoSalita));
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = new Vector3(transform.position.x, maxHight, transform.position.z);
yield return null;
The maxHight is simply 4f and TempoSalita is 2f. The coroutine is started in an OnTriggerEnter and it is working fine, the object is reaching the y of 4f and it exits the while in 2 seconds.
THE PROBLEM
Basically, elapsedTime / TempoSalita is becoming 1 after 2 seconds, as it should be, but the object reaches the ending position after like 0.3 seconds, when elapsed/TempoSalita is 0.2 and it makes no sense to me. Vector3.Lerp should go from startpos to endpos in the time of the t value to go from 0 to 1. But it goes to the final position in 0.2 seconds and I don't have a clue why.
WHAT I TRIED
I have tried to Debug.Log the elapsedTime and it is changing fine, tried to use only Mathf.Lerp between the y values and it does the same thing. There is nothing else in that script that can affect it, this is how the Coroutine starts:
void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Saltino"))
{
StartCoroutine(InVolo());
}
}
It starts only one time. Do you know what can cause this strange problem?