I've been using Lerp wrong, in case someone else has too

So I’ve used Lerp for different things since I found it and have run into issues with it slowing down. Turns out I was doing it wrong the whole time. In case somebody else has the same problem the basic idea is this…

Lerp( some start position, some end position, time value)

I had been changing the start position, which resulted in the thing I was lerping slowing down as it got closer to its destination. What I believe should happen is the time value should change instead, from 0 for start position, to 1 at the end position.

I’m drawing a blank on how to get the math to work for converting a duration to a factor between 0 and 1 taking into account frame rate. Something like…

Edit: timeFactor += Time.deltaTime * duration / duration; // I think this is correct

Hi,

(duration / duration) is 1.

0 and 1 represent a percentage: 0% and 100%. The question is: 0% and 100% of what?

Yeah, it eventually clicked. Had to dust off the old algebra skills. Maths make my head hurt sometimes :stuck_out_tongue: Doing the duration / duration got 1, and if I multiplied the top duration by Time.deltaTime I would get what percentage of duration had happened on the previous frame. So as an example if the program was running at 10 frames per second and I wanted the Lerp to take 2 seconds it would be…

timeFactor += .1 * 2 / 2
timeFactor += .1

Then just keep adding up timeFactor every frame until it reached 1. Don’t know why it took so long for this to click for me. Needless to say my Lerps are working much better now!

Edit: Although, now that I look at it actually written down… the 2’s cancel each other out don’t they? Maybe all I needed in the first place was that Time.deltaTime… hmmm

Indeed, they cancel each other out, or rather: (2 / 2) = 1. x * 1 = x.

You need to define a max duration value, e.g. 3 seconds. 3 seconds would be equivalent to 1.
Then you could calculate the percentage based on the elapsed time and clamp the value between 0 and 1 if the Lerp method does not do the latter automatically.

Your idea was right but the mistake was to use the same variable twice.

Solution

timeValue = elapsedTime / duration would be the solution where elapsedTime could be increased by Time.deltaTime each frame. This is what I usually do in coroutines. With Mathf.Clamp, it would be: timeValue = Mathf.Clamp(elapsedTime / duration, 0f, 1f).

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms