-2

I've just recently been introduced to Time.deltaTime and lerping and have been kinda stuck for the past few days.

So when I plug in Time.deltaTime for the last float and then multiply by another float variable called speed, what exactly is happening? What is Time.deltaTime doing to speed each frame that gives the end result?

Thank you!!

public class CameraMovement : MonoBehaviour
{
    public GameObject followTarget;
    public float moveSpeed;

    void Update()
    {
        if (followTarget != null)
        {
            transform.position = Vector3.Lerp(transform.position, followTarget.transform.position, moveSpeed * Time.deltaTime); 
        } 
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Bretinat0r
  • 61
  • 5

2 Answers2

2

Vector3.Lerp expects a factor between 0 and 1 and interpolates the two positions so

  • 0 would mean transform.position
  • 1 would mean followTarget.transform.position

any other value between those the interpolation between them meaning something like

transform.position + (followTarget.transform.position - transform.position) * factor;

Time.deltaTime = time past since last frame rendered so most likely a value close to 0.017 (for 60FPS). You can calculate by yourself what value this gives you in average for moveSpeed * 0.017.


It looks like what you are actually looking for is rather Vector3.MoveTowards

void Update()
{
    if (followTarget != null)
    {
        transform.position = Vector3.MoveTowards(transform.position, followTarget.transform.position, moveSpeed * Time.deltaTime); 
    }   
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
0

Using Time.deltaTime * scalar in Lerp is perfectly fine, but it's not the "expected" way to use it.

LERP means "Linear intERPolation". With this mathematic tool, you are able to interpolate a value between two others using a linear function ( y = ax + b ) and a coefficient t between 0 and 1.

Supposing you are trying to get a position (C) between two others (A and B) (like your problem), you have the folowing drawing :

alt text

1°) If the initial and destination position does not change, having the parameter t vary between 0 and 1, the movement curve will be perfectly straight : the speed will be the same over time.

transform.position = Vector2.Lerp(InitialPosition, DestinationPosition, t ); // t from 0 to 1

2°) However, having t (almost) not vary over time (with Time.deltaTime), but chaning the position of A, the movement will decelerate over time, because you take a fixed percentage of the remaining distance each time. Since the distance decrease over time, you travel less distance over time too

transform.position = Vector2.Lerp(transform.position, DestinationPosition, 0.017 ); // 0.017, approx of Time.deltaTime at 60FPS

alt text

Hellium
  • 7,206
  • 2
  • 19
  • 49