Framerate affects speed of Lerp function

Hey!
I have this code

	public IEnumerator MoveExample(Vector3 newPosition, float time)
	
	{
		float elapsedTime = 0;
		while(elapsedTime < time)
		{
			transform.position = Vector3.Lerp (transform.position, newPosition, (elapsedTime/time));
			elapsedTime += Time.deltaTime;
			yield return null;
		}
	}
}

When changing framerate (quality setting of game), the lerping goes faster/slower. Why do this occur when I use Time.deltatime?

Best regards

1 Answer

1

Are you calling “MoveExample” in an Update? (The use of .deltaTime indicates to me that you may be)

Coroutines are not garaunteed to run every frame or even only once per frame. It’s run according to a scheduler which may try to keep the coroutine aligned, but may not be able to do so.

Two alternatives:

  • Use FixedUpdate, .fixedDeltaTime and yield new WaitForFixedUpdate ();
  • Or use Time.time inside the routine to record the current time, then check it on the next execution of the coroutine body to get the difference in time.

Time.time is time in seconds since the beginning of the scene or game. It's not the same as deltaTime. Inside a coroutine, .deltaTime will return the time the last frame took between frames, not the time the last coroutine difference was called. If you're doing Time.time (this) - Time.time (last) vs. Time.deltaTime inside Update() they will indeed be the same since it will be aligned to the frame time. A coroutine is not necessarily aligned to frame time and Time.deltaTime is not recalculated for coroutines. It holds the last frame time.

Okey, so now I tried this, same results.. public IEnumerator MoveMenuSystem(Vector3 newPosition, float time) { float startTime = Time.time; while(Time.time < startTime + time) { transform.position = Vector3.Lerp (transform.position, newPosition, ((Time.time - startTime)/time)); yield return null; } }

I found the problem, it was as you said earlier, but I only needed to use: yield return new WaitForFixedUpdate(); instead of yield return null; Thanks for helping

That should move it in exactly the same time no matter the frame rate. Can you throw in a couple statements: At the start: Debug.Log("Start"); Debug.Log(Time.time); And then at the end: Debug.Log("End"); Debug.Log(Time.time); Debug.Log(Time.time - startTime); What are the results after two different executions?

I got with correct method: Quality Fastest Start 1.370207 End 2.38 1.009793 Quality Fantastic Start 2.765125 End 3.78 1.014875