Player movement with lerp is jerky.

Hey!I have a question! I’ve got this piece of code:

        ...
        if (TargetChanged(Target, TarLastPos))
        {
            if(isLerping)
            {
                StopCoroutine("LerpPlayer");
            }
            StartCoroutine(LerpPlayer(0.5f));
        }
    }
    //FUNCTIONS
    bool TargetChanged(Transform target, Vector3 lastPos)
    {
        if (
            //Target moved a tad
            Mathf.Abs(target.position.x - lastPos.x) > 0.01f ||
            Mathf.Abs(target.position.y - lastPos.y) > 0.01f ||
            Mathf.Abs(target.position.z - lastPos.z) > 0.01f
            )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    //Move player so it is in fron of camera

    IEnumerator LerpPlayer(float duration)
    {
        isLerping = true;
        Vector3 StartingPos = Player.transform.position;
        float StartTime = Time.time;
        float MovementPercent = 0f;
        while (MovementPercent < 1)
        {
            MovementPercent = (Time.time - StartTime) / duration;
            this.transform.position = Vector3.Lerp(StartingPos, Target.position, MovementPercent);
            yield return null;
        }
        isLerping = false;
        this.transform.position = Target.position;
    }

What it should do:It is meant to make the player’s position get lerped to where the camera is pointing(indicated by the Vector3 Target) and because it is a Lerp, I need it to be in a IEnumerator,but that also means to not cause imense lag i set up a function to detect if the camera(Target) changed and so it stops the coroutine and start’s it again, this time having the new Vectors.

What it does: It works…sort of. The player is “jolty” indicated in the gif, and I am not quite sure why, it should be smooth…

P.S. I couldn’t find any question/answer that solved my problem yet, but I might have missed the answer i was looking for.

Gif: Screen capture - 0ade1715343fc82ce4a580359a7f4620 - Gyazo

[preview of external content removed for GDPR compliance as it was including 3rd party cookies]

Looks like you are running the camera and object in different update loops.

Try yielding on WaitForFixedUpdate instead.

If this is for mobile, yielding like that is a performance problem, and you’d be better off putting it in the FixedUpdate function.