Reputation: 1240
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.
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.
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.
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.
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?
Upvotes: 2
Views: 6510
Reputation: 4591
It could be the condition you are using which seems a bit suspect to me.
Generally I would write this a bit differently, something like..
var t = 0f;
var start = transform.position;
var target = new Vector3(transform.position.x, maxHight, transform.position.z);
while (t < 1)
{
t += Time.deltaTime / TempoSalita;
if (t > 1) t = 1;
transform.position = Vector3.Lerp(start, target, t);
yield return null;
}
First you have your start and target values created before altering the position. The t value will increase until it reaches (or passes) 1. Since we do not want t to go beyond 1 we do a check before applying the lerp. Our t value is calculated outside of the lerp to make it clear and easy to read/modify.
The above will run for time specified and does not require the extra lines at the end since t will eventually be exactly 1.
Upvotes: 7