Search Unity

Jittering camera follow with Vector3.Lerp in LateUpdate

Discussion in 'Scripting' started by ElnuDev, Feb 23, 2020.

  1. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    I'm having a weird thing going on with camera follow. I've got all of my player movement in
    FixedUpdate
    , and then my camera follow script running in
    LateUpdate
    to prevent stutter. Now, here is the weird thing. If I do a simple follow by setting the camera position to the target position:
    Code (CSharp):
    1. transform.position = targets[0].transform.position + positionOffset;
    I have no problem whatsoever. However, if I instead do a linearly interpolated follow using
    Vector3.Lerp
    :
    Code (CSharp):
    1. transform.position = Vector3.Lerp(transform.position, targets[0].transform.position + positionOffset, Time.deltaTime * positionSmoothSpeed);
    The target starts to jitter uncontrollably. Any thoughts? I've tried a bunch of things and nothing fixes it. Thanks in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    If you are following a physics object, you want to have your camera in FixedUpdate() as well. The source of the jitter is that there are a different number of calls made to FixedUpdate() vs Update and LateUpdate(). For the latter two, they are called an identical number of times each frame, whereas FixedUpdate() is different.

    If you're not following a physics object, just use Update() for both, or perhaps LateUpdate() for the camera.

    It's possible there is something else going on with the lerp, as I don't know how your positionOffset and/or positionSmoothSpeed values were defined. Just know the third argument to lerp is always clamped from 0.0f to 1.0f.
     
    Radivarig and ElnuDev like this.
  3. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    Ok! I'm following a physics object, so I'll switch to using
    FixedUpdate
    and
    Time.fixedDeltaTime
    . Thanks for the help!
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697